ASP.NET MVC项目登出报错:未指定AuthenticationScheme,无默认登出方案
问题原因与解决方法
错误根源
你遇到的InvalidOperationException是因为:
- 调用
HttpContext.SignOutAsync()时未指定具体的认证方案 - 项目的认证配置中没有设置
DefaultSignOutScheme,框架无法确定使用哪种认证逻辑处理登出操作
两种解决方式
方式一:完善认证配置(推荐)
在项目的Startup.cs(.NET Framework/.NET Core 3.x及更早)或Program.cs(.NET 5+)中,配置认证服务时明确设置默认方案,以Cookie认证为例:
Startup.cs(ConfigureServices方法)
using Microsoft.AspNetCore.Authentication.Cookies; public void ConfigureServices(IServiceCollection services) { // 其他服务配置... services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.LoginPath = "/Account/Login"; // 登录跳转路径 // 可添加其他Cookie认证配置,比如过期时间、退出路径等 }); // 其他配置... }
Program.cs(.NET 5+)
using Microsoft.AspNetCore.Authentication.Cookies; var builder = WebApplication.CreateBuilder(args); // 其他服务配置... builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.LoginPath = "/Account/Login"; }); var app = builder.Build(); // 中间件配置... app.UseAuthentication(); app.UseAuthorization(); // 其他中间件...
如果需要更明确区分默认方案,也可以单独指定DefaultSignOutScheme:
services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultSignOutScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => { options.LoginPath = "/Account/Login"; });
方式二:在登出方法中指定认证方案
直接修改你的Logout方法,调用SignOutAsync时传入具体的认证方案名称(同样以Cookie认证为例):
using Microsoft.AspNetCore.Authentication.Cookies; public async Task<IActionResult> Logout() { await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); HttpContext.Session.SetString(SDApi.SessionToken, ""); return RedirectToAction("Index", "Home"); }
为什么教程中能正常运行?
大概率是教程里的项目模板或配置步骤中,已经默认添加了上述认证方案的配置,而你在搭建项目时遗漏了这部分内容。
内容的提问来源于stack exchange,提问作者Mnda90
相关产品推荐
相关产品推荐

