I am using ASP.NET MVC3
and running the website on Windows Server 2003
. I'm trying to figure out how to handle all HTTP errors. I have implemented code but I sometimes get a 403 error displayed in the browser when a 404 error is returned.
Here is my code that I have implemented:
In my global.asax.cs
:
protected void Application_Error(object sender, EventArgs e)
{
MvcApplication app = (MvcApplication)sender;
HttpContext context = app.Context;
Exception exception = app.Server.GetLastError();
context.Response.Clear();
context.ClearError();
HttpException httpException = exception as HttpException;
RouteData routeData = new RouteData();
routeData.Values["controller"] = "Error";
routeData.Values["action"] = "Index";
routeData.Values["httpException"] = httpException;
Server.ClearError();
IController errorController = new ErrorController();
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}
ErrorController.cs
file:
public class ErrorController : Controller
{
public ActionResult Index()
{
ErrorModel model = new ErrorModel();
HttpException httpException = RouteData.Values["httpException"] as HttpException;
int httpCode = (httpException == null) ? 500 : httpException.GetHttpCode();
switch (httpCode)
{
case 403:
//Response.StatusCode = 403;
model.Heading = "Forbidden";
model.Message = "You aren't authorised to access this page.";
break;
case 404:
//Response.StatusCode = 404;
model.Heading = "Page not found";
model.Message = "We couldn't find the page you requested.";
break;
case 500:
default:
Response.StatusCode = 500;
model.Heading = "Error";
model.Message = "Sorry, something went wrong. It's been logged.";
break;
}
Response.TrySkipIisCustomErrors = true;
return View(model);
}
}
I have nothing set in my web.config.
I want it to display the correct error when the user is trying to access my directories such as app_code
and similar directories. Is this possible?
When I type in http://localhost:43596/app_code
then I see that it seems to be a 404 error but it displays the default 403 error page of IE. How do I get my code to display the correct HTTP error message?
The reason why I want it this way is because I need to log all attempts if a user is trying to sabotage the site in any way. I want to be able to see who is doing the wrong accessing.