First off, I'm not posting this lightly. I've just spent a near-record half a day trying to solve this.
I'm developing an ASP.NET MVC website using Visual Studio 2012 on a laptop. I have implemented error-handling, which works, by adding this code to my GLOBAL.ASAX file using this approach:
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Server.ClearError();
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("action", "Index");
routeData.Values.Add("exception", exception);
if (exception.GetType() == typeof(HttpException))
{
routeData.Values.Add("statusCode", ((HttpException)exception).GetHttpCode());
}
else
{
routeData.Values.Add("statusCode", 500);
}
IController controller = new ErrorController();
controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
Response.End();
}
I've got a view which generates an error in the Razor mark-up:
@{
// trigger an error
int i =1/0;
}
When I browse to this view, it triggers an error, taking me to controller Error, action Index, where this bit of code shows an appropriate view:
public ActionResult Index(int statusCode, Exception exception){
Response.StatusCode = statusCode;
return View(); }
So far, so good. My question is - how can I get a 404 to be handled in the same way? So if I go to a non-existent page, I get:
Things I've tried:
- Every possible arrangement of CustomErrors - On / Off in web.config
- Debugging global.asax to check it's running on application start-up
- lots of other things, I'm sure, which I've now forgotten!
The web server being used by Visual Studio is IIS 8 Express, if that's of any help.