I followed this post and created a global error handler. And I added to handle 404 error myself. however, it works fine when I test locally but once deployed to web server, my custom message is not displaying anymore. Instead, the default ugly one shows up.
In remote debug, I can trace the execution and it does get to my custom 404 error action, but somehow, the IIS took over at some point.
In my Global.asax.cs, I have:
protected void Application_Error()
{
var exception = Server.GetLastError();
var httpException = exception as HttpException;
Response.Clear();
Server.ClearError();
var routeData = new RouteData();
routeData.Values["controller"] = "Error";
routeData.Values["action"] = "General";
routeData.Values["exception"] = exception;
Response.StatusCode = 500;
if (httpException != null)
{
Response.StatusCode = httpException.GetHttpCode();
switch (Response.StatusCode)
{
case 403:
routeData.Values["action"] = "Http403";
break;
case 404:
routeData.Values["action"] = "Http404";
break;
}
}
IController errorController = new ErrorController();
var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
errorController.Execute(rc);
}
then in my ErrorHandler.cs, I have:
public ActionResult General(Exception exception)
{
// log error
return Content("General error", "text/html");
}
public ActionResult Http403(Exception exception)
{
return Content("Forbidden", "text/plain");
}
public ActionResult Http404(Exception exception)
{
return Content("Page not found.", "text/plain"); // this displays when tested locally, but not after deployed to web server.
}
}
You are right, remote IIS is taking over your 404 pages. What you need is to tell the IIS to skip custom errors setting Response.TrySkipIisCustomErrors = true;
So your code should look like this.
protected void Application_Error()
{
//...
Response.TrySkipIisCustomErrors = true;
Response.StatusCode = 404;
//...rest of your code
}
Also check this link for more information http://www.west-wind.com/weblog/posts/2009/Apr/29/IIS-7-Error-Pages-taking-over-500-Errors
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With