I want a custom error page shown for 500, 404 and 403. Here's what I have done:
Enabled custom errors in the web.config as follows:
<customErrors mode="On" defaultRedirect="~/Views/Shared/Error.cshtml"> <error statusCode="403" redirect="~/Views/Shared/UnauthorizedAccess.cshtml" /> <error statusCode="404" redirect="~/Views/Shared/FileNotFound.cshtml" /> </customErrors>
Registered
HandleErrorAttribute
as a global action filter in theFilterConfig
class as follows:public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new CustomHandleErrorAttribute()); filters.Add(new AuthorizeAttribute()); }
Created a custom error page for each of the above messages. The default one for 500 was already available out of the box.
Declared in each custom error page view that the model for the page is
System.Web.Mvc.HandleErrorInfo
For 500, it shows the custom error page. For others, it doesn't.
Is there something I am missing?
It does look like this is not all there is to displaying custom errors as I read through the code in the OnException
method of the HandleErrorAttribute
class and it is handling only 500.
What do I have to do to handle other errors?
I've done pablo solution and I always had the error (MVC4)
To get rid of this, remove the line
in FilterConfig.cs
It seems i came late to the party, but you should better check this out too.
So in
system.web
for caching up exceptions within the application such as return HttpNotFound()and in
system.webServer
for catching up errors that were caught by IIS and did not made their way to the asp.net frameworkIn the last one if you worry about the client response then change the
responseMode="Redirect"
toresponseMode="File"
and serve a static html file, since this one will display a friendly page with an 200 response code.I would Recommend to use Global.asax.cs File.
There seem to be a number of steps here jumbled together. I'll put forward what I did from scratch.
Create the
ErrorPage
controllerAdd views for these two actions (right click -> Add View). These should appear in a folder called ErrorPage.
Inside
App_Start
open upFilterConfig.cs
and comment out the error handling filter.Inside web.config add the following
<customerErrors>
entries, underSystem.Web
Test (of course). Throw an unhandled exception in your code and see it go to the page with id 500, and then use a URL to a page that does not exist to see 404.
My current setup (on MVC3, but I think it still applies) relies on having an
ErrorController
, so I use:And the controller contains the following:
And the views just the way you implement them. I tend to add a bit of logic though, to show the stack trace and error information if the application is in debug mode. So Error.cshtml looks something like this: