首页 / ASP.NET MVC / 正文

[ASP.NET MVC]在ASP.NET MVC WEB网站应用程序开发中如何处理全局错误(403错误,404错误等等)?

2276 发布于: 2018-05-11 读完约需7分钟

问题描述

在ASP.NET MVC WEB网站应用程序开发中,如何处理全局错误(403错误,404错误等等)?
需要将所有的全局错误拦截并跳转到一个特定的错误Razor视图引擎页面,比如使用控制器ErrorController来展示错误页面,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 });
    }
}

现在,网上也有不少资料可以处理这样类似的错误,如下:

  • 使用Controller.OnException()处理
  • 使用ErrorFilter处理
  • web.config配置文件中配置customErrors节点处理
  • 在全局处理文件Global.asax文件中,使用方法Appliation_Error处理

以上哪种方式实现更好呢?如何实现呢?

方案一

在ASP.NET MVC WEB网站应用程序开发中,处理全局错误(403错误,404错误等等)最好的方式是在全局处理文件Global.asax中来处理。因为我们可以在全局处理文件Global.asax中拦截所有的错误(比如:Ajax请求、403错误、404错误以及 所有的未知错误),同时,在全局处理文件Global.asax中,我们还可以获取请求的上下文信息,以方便我们对数据的分析可后续的处理。

以下是一个使用全局处理文件Global.asax拦截并处理全局错误的示例代码片段,如:

protected void Application_Error()
{
    HttpContext httpContext = HttpContext.Current;
    if (httpContext != null)
    {
        //获取当前请求的上下文信息
        RequestContext requestContext = ((MvcHandler)httpContext.CurrentHandler).RequestContext;
        //判断当前请求是否是AJAX请求
        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");
        }
    }
}

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

上一篇: [C#].NET/C#应用程序开发中如何使用WebClient向指定的远程请求地址发送(POST)数据?

下一篇: [C#]在.NET/C#应用程序开发中如何从一个已知的数组中按指定的起始和结束索引位置提取子数组呢?

本文永久链接码友网 » [ASP.NET MVC]在ASP.NET MVC WEB网站应用程序开发中如何处理全局错误(403错误,404错误等等)?

分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册