Created
January 15, 2015 09:52
-
-
Save ludo6577/b4e72f9aba6b720f7cef to your computer and use it in GitHub Desktop.
ASP.NET MVC Application_Error (404 handling) http://stackoverflow.com/questions/619895/how-can-i-properly-handle-404-in-asp-net-mvc/2577095#2577095 AND
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protected void Application_Error(object sender, EventArgs e) | |
{ | |
Exception exception = Server.GetLastError(); | |
HttpException httpException = exception as HttpException; | |
// Log the exception. | |
log.Info(String.Format("Application error: {0}:", exception)); | |
log.Info(exception.StackTrace); | |
RouteData routeData = new RouteData(); | |
routeData.Values["controller"] = "Errors"; | |
routeData.Values["requestedUrl"] = Request.Url.OriginalString; | |
if (httpException == null) | |
{ | |
return; //We ignore the rest of the method | |
//TODO: custom errors handling | |
//routeData.Values.Add("action", "Index"); | |
} | |
else | |
{ | |
switch (httpException.GetHttpCode()) | |
{ | |
case 404: | |
// Page not found. | |
routeData.Values.Add("action", "Http404"); | |
break; | |
default: | |
return; | |
} | |
} | |
HttpContext httpContext = ((MvcApplication)sender).Context; | |
httpContext.Response.Clear(); | |
httpContext.Response.ContentType = "text/html"; | |
httpContext.Response.TrySkipIisCustomErrors = true; | |
httpContext.Response.StatusCode = httpException != null ? httpException.GetHttpCode() : 500; | |
Server.ClearError(); | |
// Call target Controller and pass the routeData. | |
IController errorController = new ErrorsController(); | |
try | |
{ | |
errorController.Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData)); | |
} | |
catch (Exception ex) | |
{ | |
log.Info("Error in Global.asax: Application_Error():"); | |
log.Info(ex.StackTrace); | |
string err = "<b>Error Caught in Global.asax: Application_Error() event</b><hr><br>" + | |
"<br><b>Error in: </b>" + Request.Url.ToString() + | |
"<br><b>Error Message: </b>" + ex.Message.ToString() + | |
"<br><b>Stack Trace:</b><br>" + ex.StackTrace.ToString(); | |
Response.Write(err.ToString()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment