如何显示Http 401结果的自定义错误页面?

Mar*_* M. 11 asp.net-mvc

我有一个具有Authorize属性的控制器,如下所示:

[Authorize(Roles = "Viewer")]
public class HomeController : Controller
{
   //...
}
Run Code Online (Sandbox Code Playgroud)

我的web.config有customErrors设置如下:

<customErrors mode="On">
      <error statusCode="401" redirect="notauthorized.html"/>
  </customErrors>
Run Code Online (Sandbox Code Playgroud)

当我尝试使用非授权角色在Home控制器上调用操作时,我只得到一个空白页面.我没有被重定向到自定义页面.有任何想法吗?

Vic*_*ber 13

我很欣赏这个问题有点旧,但这可能对某人有所帮助.

对于401,您可能会看到标准的401 Unauthorized页面,即使您已将401添加到web.config中的customersrors部分.我读到在使用IIS和Windows身份验证时检查发生在ASP.NET甚至看到请求之前,因此您在Cassini上看到空白页面,在IIS上看到它自己的401.

对于我的项目,我编辑了Global.asax文件以重定向到我为401错误创建的路由,将用户发送到"Unauthorized to see this"视图.

在Global.asax中:

    void Application_EndRequest(object sender, System.EventArgs e)
    {
        // If the user is not authorised to see this page or access this function, send them to the error page.
        if (Response.StatusCode == 401)
        {
            Response.ClearContent();
            Response.RedirectToRoute("ErrorHandler", (RouteTable.Routes["ErrorHandler"] as Route).Defaults);
        }
    }
Run Code Online (Sandbox Code Playgroud)

并在Route.config中:

        routes.MapRoute(
        "ErrorHandler",
        "Error/{action}/{errMsg}",
        new { controller = "Error", action = "Unauthorised", errMsg = UrlParameter.Optional }
        );
Run Code Online (Sandbox Code Playgroud)

并在控制器中:

    public ViewResult Unauthorised()
    {
        //Response.StatusCode = 401; // Do not set this or else you get a redirect loop
        return View();
    }
Run Code Online (Sandbox Code Playgroud)


Rob*_*ban 1

据我所知,一个标准方法是有一个简单的错误控制器来处理传入的请求并根据返回的 httpstatus 代码输出适当的视图......如下所示:

  public class ErrorController : Controller
{

    [AcceptVerbs(HttpVerbs.Get)]
    public ViewResult Index()
    {

        //Check if the statuscode is HttpStatusCode.NotFound;
         if(Response.StatusCode == 401)
             return View("NotAuthorised");
        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在您的 webconfig 中指定重定向操作:

<customErrors mode="On" defaultRedirect="~/Error" />
Run Code Online (Sandbox Code Playgroud)