HTTP 405 error during login

Amra Akmadžić 40 Reputation points
2024-08-20T15:22:31.9266667+00:00

I'm developing an asp.net core MVC web application and I use Identity for authentication and authorization. My login doesn't work. After entering data and pressing the button I get a HTTP 405 error.

My view uses POST method inside my form, as well as my controller.

Here is my Account Controller:

public class AccountController : Controller
{
    private readonly VjencanjeIzSnovaDbContext _context;
    private readonly UserManager<Korisnik> _userManager;
    private readonly SignInManager<Korisnik> _signInManager;

    public AccountController(UserManager<Korisnik> userManager, SignInManager<Korisnik> signInManager, VjencanjeIzSnovaDbContext context)
    {
        _userManager = userManager;
        _signInManager = signInManager;
        _context = context;
    }

    [HttpGet]
    [Route("login")]
    public IActionResult Login()
    {
        return View(new LoginViewModel());
    }

    [HttpPost]
    public async Task<IActionResult> Login(LoginViewModel model)
    {
        if (ModelState.IsValid)
        {
            var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
            if (result.Succeeded)
            {
                return RedirectToAction("Index", "Home");
            }
            ModelState.AddModelError(string.Empty, "Neuspješan pokušaj prijave.");
        }
        return View(model);
    }
}



    public class LoginViewModel
    {
        [Required]
        public string Email { get; set; }
        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }
        
        public bool RememberMe { get; set; } = false;

        public LoginViewModel()
        {
            Email = string.Empty;
            Password = string.Empty;
        }
    }
}

Program.cs:

using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
using VjencanjeIzSnova_WebApp.Data;
using VjencanjeIzSnova_WebApp.Models;
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("LocalDb") ?? throw new InvalidOperationException("Connection string 'LocalDb' not found.");
builder.Services.AddDbContext<VjencanjeIzSnovaDbContext>(options =>
    options.UseSqlite(connectionString));
builder.Services.AddDefaultIdentity<Korisnik>(options => options.SignIn.RequireConfirmedAccount = true).AddEntityFrameworkStores<VjencanjeIzSnovaDbContext>();
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services.AddIdentity<Korisnik, IdentityRole>(options =>
{
    options.Password.RequireDigit = true;
    options.Password.RequireLowercase = true;
    options.Password.RequireUppercase = true;
    options.Password.RequireNonAlphanumeric = true;
    options.Password.RequiredLength = 6;
    options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
    options.Lockout.MaxFailedAccessAttempts = 5;
    options.SignIn.RequireConfirmedAccount = true;
})
.AddEntityFrameworkStores<VjencanjeIzSnovaDbContext>()
.AddDefaultTokenProviders();
// Add services to the container.
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.LoginPath = "/login";
        options.AccessDeniedPath = "/Account/AccessDenied";
    });
builder.Services.AddAuthorization();
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();
app.Run();

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,612 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Tiny Wang-MSFT 2,731 Reputation points Microsoft Vendor
    2024-08-21T05:22:13.62+00:00

    Hi Amra, firstly, I didn't reproduce your issue in my side without complete code (lacking of views), but I noticed that you are having your custom login page even though you already have builder.Services.AddDefaultIdentity in your application. The AddDefailtIdentity method provide us with a simplified way to add identity services to your application which is using cookie based authentication, but you have builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie at the same time.

    By the way, in asp.net core we could use AddDefaultIdentity, AddIdentity and AddIdentityCore for identification, we can see from the source code, AddDefaultIdentity uses AddIdentityCore , and

    AddIdentity provides more control and customization, including custom user types, roles, and more detailed configuration of identity options, but have both AddDefaultIdentity and AddIdentity at the same time.

    Per my understanding, you might try to follow this document to add Asp.net Core identity into your MVC app. You can do it by creating a new MVC application and selecting the Authentication type to be Individual Account.

    User's image

    Then you will use the default identity mechanism, if you want to manage the login page, you can use scaffold tool(right click on the project name in VS and choose Add -> New scaffolded item...) to load the cshtml files into your project.User's image


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Tiny Wang


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.