500 Internal Server Error page in MVC [duplicate]

房东的猫 提交于 2019-12-04 19:46:51

问题


I'm trying to set up custom errors for an MVC site. I have the 404 page working fine, but when testing a server error I get the default message:

Sorry, an error occurred while processing your request.

Instead of my custom page.

I have set this up in the web.config:

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

My error controller is as follows:

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

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

I'm testing the 500 error page by throwing an exception in one of my views:

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

Why is it that only 404 errors are handled? How can I display the error page for 500 errors?


回答1:


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.



来源:https://stackoverflow.com/questions/18744390/500-internal-server-error-page-in-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!