So my question: is it enough to add this in the global.asax
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
No because HandleErrorAttribute
will only catch error code 500 (Internal server error).
If you want to catch 404's (page not found) in addition to 500 the best way to do this is to use httpErrors
because they will also catch 404's that do not match any of your defined routes.
Custom errors will only catch 404's that match a route. For example, a 404 from: http://example.com/someNonExistantFile.html
will not be caught by custom errors (assuming no route exists that matches the URL). A 404 from http://example.com/ControllerName/someNonExistentAction will be caught by custom errors.
I setup httpErrors
like this in web.config system.webserver
section:
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="400" subStatusCode="-1" />
<remove statusCode="403" subStatusCode="-1" />
<remove statusCode="404" subStatusCode="-1" />
<remove statusCode="500" subStatusCode="-1" />
<error statusCode="400" path="/Error/BadRequest" responseMode="ExecuteURL"/>
<error statusCode="403" path="/Error/NotAuthorized" responseMode="ExecuteURL" />
<error statusCode="404" path="/Error/NotFound" responseMode="ExecuteURL" />
<error statusCode="500" path="/Error" responseMode="ExecuteURL" />
</httpErrors>
Then in my Error controller I set the http response code accordingly. Doing that prevents google and others from indexing your error pages.
Here is my ErrorController that I use:
[AllowAnonymous]
public class ErrorController : Controller
{
public ActionResult Index()
{
Response.StatusCode = 500;
return View("Error");
}
public ViewResult BadRequest()
{
Response.StatusCode = 400;
return View("BadRequest");
}
public ViewResult NotFound()
{
Response.StatusCode = 404;
return View("NotFound");
}
public ViewResult NotAuthorized()
{
Response.StatusCode = 403;
return View("NotAuthorized");
}
}