问题
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