10

我正在尝试为 MVC 站点设置自定义错误。我的 404 页面工作正常,但是在测试服务器错误时,我收到默认消息:

抱歉,处理您的请求时出现了一个错误。

而不是我的自定义页面。

我已经在 web.config 中进行了设置:

<customErrors mode="On"  defaultRedirect="~/Error/500">
    <error statusCode="404" redirect="~/Error/404" />
    <error statusCode="500" redirect="~/Error/500" />
</customErrors>

我的错误控制器如下:

public class ErrorController : Controller
{
    [ActionName("404")]
    public ActionResult NotFound()
    {
        return View();
    }

    [ActionName("500")]
    public ActionResult ServerError()
    {
        return View();
    }
}

我正在500通过在我的一个视图中抛出异常来测试错误页面:

[ActionName("contact-us")]
public ActionResult ContactUs()
{
    throw new DivideByZeroException();
    return View();
}

为什么只处理404错误?如何显示错误的错误页面500

4

1 回答 1

20

Figured this out..

It was some boilerplate code left in the Global.asax.cs when creating the project:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
   filters.Add(new HandleErrorAttribute());
}

In particular:

filters.Add(new HandleErrorAttribute());

This creates an new instance of HandleErrorAttribute which is applied Globally to all of my views.

With no customization, if a view throws an error while utilizing this attribute, MVC will display the default Error.cshtml file in the Shared folder which is where the: "Sorry, an error occurred while processing your request." came from.

From the documentation on HandleErrorAttribute:

By default, when an action method with the HandleErrorAttribute attribute throws any exception, MVC displays the Error view that is located in the ~/Views/Shared folder.

Commenting this line out solved the problem and allowed me to use custom error pages for 500 errors.

于 2013-09-11T15:28:02.223 回答