Question

I have a new MVC 4.0 solution created from scratch using VS2012 web express and IIS Express. As the tile says I changed my web.config and added the following in :

<customErrors defaultRedirect="Errors/GenericError.html" mode="On">
    <error statusCode="404" redirect="Errors/Error404.html"/>
</customErrors>

Basically when I get an exception in my controller the default MVC error.cshtml is showing the error instead of my custom page GenericError.html.

If I go to a URL that doesn't exist, my Error404.html is showing correctly but not for the generic scenario.

Any ideas how I can change this behavior?

Était-ce utile?

La solution

Sounds like you don't have the error attribute in your global filters. In an MVC 4 project you should be able to search for the class FilterConfig that was generated for you:

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

Update:

The HandleErrorAttribute global filter is for errors that occur in the MVC pipeline, such as errors in your controller as you mention.

The customErrors element in the web.config is for everything else. The HandleErrorAttribute will not honor the value you put in the defaultRedirect attribute of customErrors.

The HandleError filter will look for a shared view which you should have in your generated project shared\Error.cshtml. You can point it to a different view by setting a property on the attribute.

For example, let's say we create a new view under Shared\Errors\CustomError.cshtml, then you could register the filter like this:

filters.Add(new HandleErrorAttribute(){View = "Errors/CustomError"});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top