Cri*_*jak 5 asp.net-identity asp.net-core
使用[Authorize]属性时如何在 ASP.NET Core 上显示错误页面?
政策
services.AddAuthorization(p =>
{
p.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
p.AddPolicy("RequireTrainerRole", policy => policy.RequireRole("Trainer"));
p.AddPolicy("RequireTeamLeaderRole", policy => policy.RequireRole("Team Leader"));
p.AddPolicy("RequireUserRole", policy => policy.RequireRole("User"));
});
Run Code Online (Sandbox Code Playgroud)
控制器
[Authorize(Policy = "RequireAdminRole")]
[Area("Admin")]
public class BaseController : Controller
{
}
Run Code Online (Sandbox Code Playgroud)
如果您使用 cookie 身份验证来保护您的资源,那么您可以使用AccessDeniedPath属性重定向到错误页面:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AccessDeniedPath = "<path>"
});
Run Code Online (Sandbox Code Playgroud)
否则,您可以使用处理 403 UseStatusCodePages
app.UseStatusCodePages(new StatusCodePagesOptions()
{
HandleAsync = (ctx) =>
{
if (ctx.HttpContext.Response.StatusCode == 403)
{
//handle
}
return Task.FromResult(0);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1448 次 |
| 最近记录: |