使用[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"));
});
控制器
[Authorize(Policy = "RequireAdminRole")]
[Area("Admin")]
public class BaseController : Controller
{
}
答案 0 :(得分:2)
如果您使用Cookie身份验证来保护您的资源,那么您可以使用AccessDeniedPath
属性重定向到错误页面:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AccessDeniedPath = "<path>"
});
否则,您可以使用UseStatusCodePages
app.UseStatusCodePages(new StatusCodePagesOptions()
{
HandleAsync = (ctx) =>
{
if (ctx.HttpContext.Response.StatusCode == 403)
{
//handle
}
return Task.FromResult(0);
}
});