这个错误信息 System.InvalidOperationException: No authentication scheme was specified, and there was no DefaultChallengeScheme found
通常出现在使用 ASP.NET Core 进行 Web 开发时,表示在处理请求时没有找到指定的身份验证方案。以下是对这个问题的详细解释以及解决方案。
身份验证方案(Authentication Scheme):在 ASP.NET Core 中,身份验证方案定义了如何验证用户的身份。常见的身份验证方案包括 JWT(JSON Web Token)、Cookie 认证、OAuth 等。
常见的身份验证方案包括:
这个错误通常是由于在 Startup.cs
或 Program.cs
文件中没有正确配置身份验证方案导致的。
以下是一个示例,展示如何在 ASP.NET Core 中配置 JWT 身份验证方案:
Startup.cs
中配置(适用于 ASP.NET Core 3.x 及以下版本)public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
// 配置 JWT 身份验证
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthentication(); // 确保在 UseAuthorization 之前调用
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Program.cs
中配置(适用于 ASP.NET Core 6.0 及以上版本)var builder = WebApplication.CreateBuilder(args);
// 添加服务
builder.Services.AddControllers();
// 配置 JWT 身份验证
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
};
});
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthentication(); // 确保在 UseAuthorization 之前调用
app.UseAuthorization();
app.MapControllers();
app.Run();
通过上述配置,可以确保在处理请求时正确指定了身份验证方案,从而避免 System.InvalidOperationException
错误。确保在 Startup.cs
或 Program.cs
中正确配置了默认的身份验证方案,并且在请求处理管道中正确调用了 UseAuthentication
和 UseAuthorization
中间件。
领取专属 10元无门槛券
手把手带您无忧上云