I am learning ASP.NET Core MVC framework (.NET 8) by building a sample project: Following are the code files-
- In the Program.cs file I have the following services registered:
builder.Services.AddDbContext<ApplicationDbContext>(options=>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
//registering the Authetication Services with COOKIE Autheticaition scheme
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(option =>
{
option.LoginPath = "/UserAccess/Login";
option.ExpireTimeSpan = TimeSpan.FromMinutes(20);
});
//some line of code then..
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
- Model: UserLogin.cs
namespace LandPurchase.Models
{
public class UserLogin
{
public string? Username { get; set; }
public string? Password { get; set; }
public bool KeepLoggedIn { get; set; } = false;
}
}
- Controller : UserAccessController.cs I have the below IActionResult methods one for GET and one for POST:
public class UserAccessController : Controller
{
public IActionResult Login()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Login(UserLogin usrLogin)
{
//will perform password verification and generate Httpcontext
return View();
}
- View: Login.cshtml
@model UserLogin
<h1>User Entry according to Role</h1>
<form method="post" asp-controller="UserAccess" asp-action="Login">
<div class="mt-2 mb-3">
<input asp-for="Username" type="text" class="form-control" placeholder="Username">
</div>
<div>
<input asp-for="Password" type="password" class="form-control" placeholder="Password">
</div>
<div class="row mt-3">
<a class="col-3 ms-3 btn btn-outline-primary" role="button" >Log In</a>
<a href="#" class="col-6 ms-2 text-decoration-none text-success">Forgot password?</a>
</div>
</form>
In the Home view I have the following button, when clicked goes to the UserAccessController and display the view Login.cshtml.
<a class="btn btn-outline-primary" role="button" asp-controller="UserAccess" asp-action="Login">Click to Login</a>
My problem is when I click the Log In button from the Login.cshtml view the IActionResult of the [Httppost] does not get hit and the control does not go there. Only the method for GET gets hit when I initially load the form. Thus I am not able to perform the Login functionality. Thank you in Advance.
Tried changing the UserLogin-ViewModel to UserLogin-Model. Since I thought that it has something to do with Model Validation.