ASP.NET Core 6.0登录时出现无登录认证处理器注册错误求助
错误信息
fail: Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HMRQHOSA1VM6", Request id "0HMRQHOSA1VM6:00000001": An unhandled exception was thrown by the application.
System.InvalidOperationException: No sign-in authentication handlers are registered. Did you forget to call AddAuthentication().AddCookie("Cookies",...)?
at Microsoft.AspNetCore.Authentication.AuthenticationService.SignInAsync(HttpContext context, String scheme, ClaimsPrincipal principal, AuthenticationProperties properties)
at proyectoFinal.Controllers.AccountController.Login(String username, String password) in C:\Users\source\repos\parc\project\project\Controllers\AccountController.cs:line 35
...(省略后续栈追踪信息)
我提供的代码
Startup.cs
using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace proyectoFinal { public class Startup { private readonly IConfiguration _configuration; public Startup(IConfiguration configuration) { _configuration = configuration; } public void ConfigureServices(IServiceCollection services) { // Add authentication services services.AddAuthentication(options => { options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddCookie(options => { options.LoginPath = "/Account/Login"; options.AccessDeniedPath = "/Account/AccessDenied"; }); // Configure authorization services.AddAuthorization(options => { options.AddPolicy("AdminOnly", policy => { policy.RequireRole("Admin"); }); options.AddPolicy("ManagerOnly", policy => { policy.RequireRole("Manager"); }); options.AddPolicy("UserOnly", policy => { policy.RequireRole("User"); }); }); // Add other services and dependencies services.AddControllersWithViews(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } }
AccountController.cs
using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Mvc; namespace proyectoFinal.Controllers { public class AccountController : Controller { public IActionResult Login() { return View(); } [HttpPost] public async Task<IActionResult> Login(string username, string password) { // Perform your authentication logic here // e.g., validate the username and password against a user store // Simulate a successful authentication if (username == "admin" && password == "admin") { var claims = new[] { new Claim(ClaimTypes.Name, username), new Claim(ClaimTypes.Role, "Admin") // Assign the "Admin" role }; var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); var principal = new ClaimsPrincipal(identity); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); return RedirectToAction("Index", "Home"); } // Authentication failed ModelState.AddModelError(string.Empty, "Invalid credentials"); return View(); } [HttpPost] public async Task<IActionResult> Logout() { await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return RedirectToAction("Index", "Home"); } } }
Program.cs
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using proyectoFinal; var builder = Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.ConfigureServices((hostContext, services) => { services.AddControllersWithViews(); services.AddDbContext<SQLiteDBContext>(); // Register the SQLiteDBContext }) .Configure((hostContext, app) => { if (!hostContext.HostingEnvironment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); using (var scope = app.ApplicationServices.CreateScope()) { var services = scope.ServiceProvider; var dbContext = services.GetRequiredService<SQLiteDBContext>(); dbContext.Database.EnsureCreated(); } }); }); await builder.RunConsoleAsync();
问题原因及修复方案
问题根源
你的Program.cs完全重新定义了服务配置和中间件管道,没有使用Startup类中的任何配置。这导致Startup.cs里注册的认证服务(AddAuthentication和AddCookie)根本没有被加载到应用中,所以登录时会提示没有注册登录认证处理器。
修复方案(二选一)
方案1:修改Program.cs,使用Startup类配置
将Program.cs修改为使用Startup类,复用已写好的认证和授权配置:
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using proyectoFinal; var builder = WebApplication.CreateBuilder(args); // 使用Startup类配置服务 builder.Services.AddControllersWithViews(); builder.Services.AddDbContext<SQLiteDBContext>(); var startup = new Startup(builder.Configuration); startup.ConfigureServices(builder.Services); var app = builder.Build(); // 使用Startup类配置中间件 startup.Configure(app, app.Environment); // 初始化数据库(原Program.cs中的逻辑) using (var scope = app.Services.CreateScope()) { var services = scope.ServiceProvider; var dbContext = services.GetRequiredService<SQLiteDBContext>(); dbContext.Database.EnsureCreated(); } app.Run();
方案2:直接在Program.cs中添加认证和授权配置
保持ASP.NET Core 6.0顶级语句风格,直接在Program.cs里添加认证服务注册和中间件调用:
using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using proyectoFinal; var builder = WebApplication.CreateBuilder(args); // 添加认证服务 builder.Services.AddAuthentication(options => { options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddCookie(options => { options.LoginPath = "/Account/Login"; options.AccessDeniedPath = "/Account/AccessDenied"; }); // 添加授权策略 builder.Services.AddAuthorization(options => { options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin")); options.AddPolicy("ManagerOnly", policy => policy.RequireRole("Manager")); options.AddPolicy("UserOnly", policy => policy.RequireRole("User")); }); // 添加其他服务 builder.Services.AddControllersWithViews(); builder.Services.AddDbContext<SQLiteDBContext>(); var app = builder.Build(); // 配置中间件管道 if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); // 注意顺序:先认证,再授权 app.UseAuthentication(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); // 初始化数据库 using (var scope = app.Services.CreateScope()) { var services = scope.ServiceProvider; var dbContext = services.GetRequiredService<SQLiteDBContext>(); dbContext.Database.EnsureCreated(); } app.Run();
关键注意点
- 中间件顺序必须正确:
UseAuthentication()必须在UseAuthorization()之前调用,否则认证信息无法被授权中间件读取。 - 确保认证服务(
AddAuthentication+AddCookie)被正确注册到服务容器中。
内容的提问来源于stack exchange,提问作者Programming_guy

