c# - 如何解决此“未指定身份验证方案,并且未找到 DefaultChallengeScheme”
问题描述
[![消息错误]] [1]: https://i.stack.imgur.com/ciKCK.png
我的观点是,如果有人在没有登录的情况下进入授权页面,它将被重定向到登录页面。
这是我的代码(.NET Core 3.1):
我的控制器
[Authorize]
public IActionResult Username()
{
var lstUsername = _dbContext.MT_USERNAME.ToList();
return View(lstUsername);
}
我的启动.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<GPServiceDbContext>(options =>
{
options.UseSqlServer(xxx);
});
services.AddControllersWithViews();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(1);
});
}
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.UseStatusCodePages(context =>
{
var response = context.HttpContext.Response;
if (response.StatusCode == (int)HttpStatusCode.Unauthorized ||
response.StatusCode == (int)HttpStatusCode.Forbidden)
response.Redirect("/Login/Login");
return Task.CompletedTask;
});
app.UseAuthorization();
app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Login}/{action=Login}/{id?}");
});
}
解决方案
因为您没有在 ConfigureServices 中配置身份验证服务。以cookie认证为例。需要指定默认的 authenticationScheme。
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = DefaultAuthenticationTypes.ApplicationCookie;
})
.AddCookie(DefaultAuthenticationTypes.ApplicationCookie, options =>
{
options.LoginPath = "/Login";
options.LogoutPath = "/Logout";
});
//...
}
关于这一点,您也可以参考这些文档。
推荐阅读
- java - 如何在 Ubuntu 18.04.2 LTS 上使用 OpenJDK 8 运行 Java FX?
- azure - 多个域的 Azure AD 身份验证
- angular2-routing - Angular 7 将应用程序页面重定向到 index.html
- python - Pygame - 运动漂移
- fortran - 哪个 dgemm 调用最快?
- javascript - 从 react-native 中的数组中的对象获取密钥
- wix - Wix 安装程序在升级后隐藏正在使用的应用程序警告
- python - 将重复记录合并为一个,同时进行近似重复数据删除
- angular - 运行“ng test”命令时出错
- python - 如何在if语句中更改变量的值并在python中全部应用