为什么MVC4会返回带有customErrors的500?

时间:2012-06-13 12:06:05

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

我有一个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" />

感谢您的帮助。

1 个答案:

答案 0 :(得分:4)

这就是[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 - &gt; filters.Add(new HandleErrorAttribute());中注册)。 / p>

相关问题