ASP.NET MVC 5 错误处理 [英] ASP.NET MVC 5 error handling

查看:41
本文介绍了ASP.NET MVC 5 错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

We want to handle 403 errors, 404 errors, all errors due to a MySpecialDomainException and provide a default error page for all other errors (including errors in the IIS configuration!). All errors should return proper Razor views, it would be very nice to have an ErrorController in front of the views. E.g. something like this:

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 上找到许多不同的方法来做到这一点,其中一些很可能已经过时了.其中:

Currently you find many different ways to do that on the www, some most probably outdated. Among those:

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

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

Q1: What is the recommended way to fulfill our requirements with ASP.NET MVC 5?

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

Also we want to catch errors occurring in the IIS host. Q2: To prevent that IIS has to handle any 404s we thought about adding a default route matching all possible URLs - is this recommendable? Better to register instead for IIS' 404s as well?

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

Q3: Is it even possible to register an IIS error page which goes back to a controller, or is IIS capable of ASPX / static HTML only?

推荐答案

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

The best way is using Global.Asax, because you can manage all types of errors (Ajax calls/ all of unexpected Errors). with others you can't do it.

像这样:

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");
        }
    }
}

这篇关于ASP.NET MVC 5 错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆