如何在ASP.NET Core上显示非授权页面

时间:2016-11-01 08:29:36

标签: asp.net-core asp.net-identity

使用[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
{
}

1 个答案:

答案 0 :(得分:2)

如果您使用Cookie身份验证来保护您的资源,那么您可以使用AccessDeniedPath属性重定向到错误页面:

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AccessDeniedPath = "<path>"
        });

否则,您可以使用UseStatusCodePages

处理403
app.UseStatusCodePages(new StatusCodePagesOptions()
 {
     HandleAsync = (ctx) =>
     {
          if (ctx.HttpContext.Response.StatusCode == 403)
          {
               //handle
          }

          return Task.FromResult(0);
     }
 });