【问题标题】:Why would MVC4 return a 500 with customErrors on?为什么 MVC4 会在 customErrors 开启的情况下返回 500?
【发布时间】:2013-02-07 19:30:01
【问题描述】:

我有一个 MVC4 站点,它有一个不错的 customError 页面,如果你在 IE 中关闭了友好错误,但它不会显示你是否打开了友好错误。我不知道为什么 MVC4 应该只显示我的错误页面时会返回 500,但它确实存在。这是一个例子(我不得不把它写成代码,因为 SO 在 IP 号上翻了出来):

http://192.52.51.45/web/Trip/Index/f32e4bc5-9e06-4bb8-8d43-d43b8c9a014c

要让网站返回 200 并只显示我的错误页面,我需要进行哪些配置更改?不是我对默认 Web.config 的唯一更改是 customErrors:

<customErrors mode="On" />

感谢您的帮助。

【问题讨论】:

    标签: iis-7.5 asp.net-mvc-4


    【解决方案1】:

    [HandleError] 全局属性就是这样实现的:

    public virtual void OnException(ExceptionContext filterContext)
    {
        if (filterContext == null)
        {
            throw new ArgumentNullException("filterContext");
        }
        if (!filterContext.IsChildAction && (!filterContext.ExceptionHandled && filterContext.HttpContext.IsCustomErrorEnabled))
        {
            Exception innerException = filterContext.Exception;
            if ((new HttpException(null, innerException).GetHttpCode() == 500) && this.ExceptionType.IsInstanceOfType(innerException))
            {
                string controllerName = (string) filterContext.RouteData.Values["controller"];
                string actionName = (string) filterContext.RouteData.Values["action"];
                HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
                ViewResult result = new ViewResult {
                    ViewName = this.View,
                    MasterName = this.Master,
                    ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                    TempData = filterContext.Controller.TempData
                };
                filterContext.Result = result;
                filterContext.ExceptionHandled = true;
                filterContext.HttpContext.Response.Clear();
                filterContext.HttpContext.Response.StatusCode = 500;
                filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
            }
        }
    }
    

    注意它如何将状态码设置为 500 并呈现 ~/Views/Shared/Error.cshtml 视图。当启用自定义错误时,所有这些都会发生。

    顺便说一下,这是在这种特殊情况下使用的语义正确的 HTTP 状态代码。如果您没有找到请求的资源,则为 404。仅当服务器成功处理用户请求时才应使用 200。

    如果由于某种原因您不喜欢这种行为,您可以随时编写自定义全局错误处理属性并替换默认属性(在~/App_Start/FilterConfig.cs -> filters.Add(new HandleErrorAttribute()); 中注册)。

    【讨论】:

    • App_Start *.config 文件是 MVC 4 RC 的新文件,当您创建新的 MVC 4 应用程序时,测试版没有此文件。
    • 是的,没错。在 ASP.NET MVC 4 Beta 中,一切都在 Global.asax 中。
    • 忘记了 MVC 现在是开源的!我应该想到的。感谢您的洞察力,我可能只是围绕它编写一些逻辑,而不是对我的业务逻辑使用错误处理! ;)
    猜你喜欢
    • 1970-01-01
    • 2020-02-07
    • 2020-11-04
    • 2015-03-06
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多