ASP.NET MVC 5错误处理

D.R*_*.R. 38 c# error-handling asp.net-mvc asp.net-mvc-5 asp.net-mvc-5.1

我们希望处理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 });
    }
}
Run Code Online (Sandbox Code Playgroud)

目前,您可以在www上找到许多不同的方法,有些可能已经过时了.在这些:

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

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

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

问题3:甚至可以注册一个可以返回控制器的IIS错误页面,还是仅支持ASPX /静态HTML的IIS?

nat*_*l88 52

最好的方法是使用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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


dus*_*ris 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


Mah*_*esh 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