39

我们要处理 403 错误、404 错误、由于 a 引起的所有错误,MySpecialDomainException并为所有其他错误(包括 IIS 配置中的错误!)提供默认错误页面。所有错误都应该返回正确的 Razor 视图,ErrorController在视图前面有一个非常好。例如这样的:

public class ErrorController : Controller
{
    public ViewResult NotFound () { return View(); }
    public ViewResult Forbidden () { return View(); }
    public ViewResult Default ()
    {
        var ex = ObtainExceptionFromSomewhere();
        if(ex is MySpecialDomainException)
            return View("MySpecialDomainException", new ErrorModel { Exception = ex });

        return View("GeneralError", new ErrorModel { Exception = ex });
    }
}

目前,您可以在 www 上找到许多不同的方法,其中一些很可能已经过时。在这些:

  • Controller.OnException()
  • 错误过滤器
  • web.config 中的 customErrors 元素
  • Global.asax 的 Application_Error 中的处理

Q1:使用 ASP.NET MVC 5 满足我们要求的推荐方法是什么?

我们还想捕捉 IIS 主机中发生的错误。Q2:为了防止 IIS 必须处理任何 404,我们考虑添加一个匹配所有可能 URL 的默认路由 - 这是否值得推荐?最好也注册 IIS 的 404?

Q3:是否可以注册一个返回到控制器的 IIS 错误页面,或者 IIS 是否仅支持 ASPX / 静态 HTML?

4

3 回答 3

56

最好的方法是使用 Global.Asax,因为您可以管理所有类型的错误(Ajax 调用/所有意外错误)。和别人一起你做不到。

像这样:

protected void Application_Error()
{
    HttpContext httpContext = HttpContext.Current;
    if (httpContext != null)
    {
        RequestContext requestContext = ((MvcHandler)httpContext.CurrentHandler).RequestContext;
        /* When the request is ajax the system can automatically handle a mistake with a JSON response. 
           Then overwrites the default response */
        if (requestContext.HttpContext.Request.IsAjaxRequest())
        {
            httpContext.Response.Clear();
            string controllerName = requestContext.RouteData.GetRequiredString("controller");
            IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
            IController controller = factory.CreateController(requestContext, controllerName);
            ControllerContext controllerContext = new ControllerContext(requestContext, (ControllerBase)controller);

            JsonResult jsonResult = new JsonResult
            {
                Data = new { success = false, serverError = "500" },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
            jsonResult.ExecuteResult(controllerContext);
            httpContext.Response.End();
        }
        else
        {
            httpContext.Response.Redirect("~/Error");
        }
    }
}
于 2014-06-09T15:32:20.083 回答
41

没有适用于所有应用程序的黄金解决方案。

您可以使用 web.config 中的 httpErrors 显示友好的错误页面。与 customErrors 不同,这是一个 IIS 级别设置,甚至会为您显示一个友好的错误页面,用于显示不是来自 ASP.NET 内部的错误。

对于错误记录,我建议使用像 ELMAH 这样的 HttpModule: https ://code.google.com/p/elmah/

我为此写了一篇完整的博客文章,并在其中解释了错误处理的不同方式:http: //dusted.codes/demystifying-aspnet-mvc-5-error-pages-and-error-logging

于 2015-04-06T23:09:11.450 回答
7

处理错误的更好方法是扩展 handleerror 属性。处理错误属性具有以下优点

  • 使用 HandleErrorAttribute,我们可以更好地控制异常处理。HandleError 允许我们为不同的控制器和操作轻松地处理错误,在 Application_Error 中,我们借助 switch 循环来获得此功能。

  • 一旦你进入 Application_Error,你就离开了 MVC,你将失去 ControllerContext,然后我们就不能做很多事情,而 HandleError 很容易做到。

有关如何扩展错误处理属性和优势,请参阅以下帖子

[HandleError] 相对于 Application_Error 的优势

http://maheshde.blogspot.com.au/2012/09/error-handing-with-mvc-using-custom.html

http://www.codeproject.com/Articles/731913/Exception-Handling-in-MVC

于 2014-12-04T05:31:52.883 回答