针对404、401和其他异常的ASP.NET MVC4错误处理

针对404、401和其他异常的ASP.NET MVC4错误处理,asp.net,asp.net-mvc,Asp.net,Asp.net Mvc,我正在努力理解如何正确处理ASP.NET MVC4中的错误。例如,我使用“Internet应用程序”模板创建了一个新的MVC4项目,并更新了我的家庭控制器以测试一些错误情况: public class HomeController : Controller { public ActionResult Index() { ViewBag.Message = "Hello"; return View(); } public Actio

我正在努力理解如何正确处理ASP.NET MVC4中的错误。例如,我使用“Internet应用程序”模板创建了一个新的MVC4项目,并更新了我的家庭控制器以测试一些错误情况:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Message = "Hello";
        return View();
    }

    public ActionResult About()
    {
        throw new HttpException(401, "Not Authorized");
    }

    public ActionResult Contact()
    {
        throw new Exception("Oh no, some error occurred...");
    }
}
我在web.config文件中启用了customErrors:

<customErrors mode="On"></customErrors>
404页面工作正常,但我根本没有401页面。相反,当我尝试访问
控制器上的
关于
操作时,会得到~/Error/Trouble视图(指定为
默认重定向


为什么我的自定义401重定向页面不工作?

ASP.NET在内部使用401将用户重定向到登录页面。无论你打算在哪里扔401,而不是403

如果您确实需要返回401而不是403,那么您可以使用:

HttpContext.Current.Response.SuppressFormsAuthenticationRedirect = true

我遇到了一个类似的问题,尽管web.config发生了更改,但我无法将401个错误转到我的页面

对于401,您可能会看到标准的401未经授权页面,即使您已将401添加到web.config中的customerrors部分。我了解到,当使用IIS和Windows身份验证时,检查发生在ASP.NET看到请求之前,因此您可以看到它自己的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);
        }
    }
在Route.config中:

        routes.MapRoute(
        "ErrorHandler",
        "Error/{action}/{errMsg}",
        new { controller = "Error", action = "Unauthorised", errMsg = UrlParameter.Optional }
        );
在控制器中:

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

这是一个很好(而且非常简单)的解决方案,谢谢!为了让其他阅读此问题的人感兴趣,这里有另一条很好的评论描述401和403之间的区别:有趣,我不知道这一点!谢谢:).NET4.5特定,但解决了FormsAuthentication接管所有401的问题。
    public ViewResult Unauthorised()
    {
        //Response.StatusCode = 401; // Do not set this or else you get a redirect loop
        return View();
    }