当使用ASP.NET Core身份验证时,如果未指定身份验证方案或找不到默认的身份验证方案,可能会出现“No authenticationScheme was specified, and there was no DefaultChallengeScheme found”错误。此错误通常在尝试使用未配置的身份验证方案时发生,或者没有为默认身份验证方案指定值。
以下是解决此错误的一些方法,包括代码示例:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
options.Cookie.Name = "YourCookieName";
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
options.SlidingExpiration = true;
});
// 其他服务配置...
services.AddControllers();
}
[Authorize]
public class HomeController : Controller
{
// 控制器代码...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// 其他中间件配置...
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
public async Task Login()
{
// 其他代码...
await HttpContext.ChallengeAsync("YourAuthenticationScheme");
// 其他代码...
}
请根据您的具体情况检查和调整代码示例中的身份验证方案和配置。这些解决方法应该帮助您解决“No authenticationScheme was specified, and there was no DefaultChallengeScheme found”错误。