Created
June 14, 2013 09:21
-
-
Save bitsprint/5780599 to your computer and use it in GitHub Desktop.
ASP.NET MVC Application Global
This file contains hidden or 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
| namespace Web | |
| { | |
| using System; | |
| using System.Web; | |
| using System.Web.Http; | |
| using System.Web.Mvc; | |
| using System.Web.Optimization; | |
| using System.Web.Routing; | |
| using NLog; | |
| using Web.Controllers; | |
| public class MvcApplication : HttpApplication | |
| { | |
| protected void Application_Start() | |
| { | |
| BundleTable.Bundles.RegisterTemplateBundles(); | |
| var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter; | |
| xml.UseXmlSerializer = true; | |
| } | |
| protected void Application_Error(object sender, EventArgs e) | |
| { | |
| var exception = Server.GetLastError(); | |
| LogManager.GetCurrentClassLogger().ErrorException("An error has occured", exception); | |
| Response.Clear(); | |
| if (exception.Message.Contains("did not return a controller for the name")) | |
| { | |
| exception = new HttpException(404, exception.Message); | |
| } | |
| var httpException = exception as HttpException; | |
| var ua = exception as UnauthorizedAccessException; | |
| var routeData = new RouteData(); | |
| routeData.Values.Add("controller", "Error"); | |
| if (httpException == null) | |
| { | |
| if (ua == null) | |
| { | |
| routeData.Values.Add("action", "ServerError500"); | |
| } | |
| else | |
| { | |
| routeData.Values.Add("action", "Unauthorised403"); | |
| } | |
| } | |
| else | |
| { | |
| switch (httpException.GetHttpCode()) | |
| { | |
| case 401: | |
| routeData.Values.Add("action", "Unauthorised403"); | |
| break; | |
| case 404: | |
| routeData.Values.Add("page", exception.Message); | |
| routeData.Values.Add("action", "PageNotFound404"); | |
| break; | |
| case 500: | |
| routeData.Values.Add("action", "ServerError500"); | |
| break; | |
| default: | |
| routeData.Values.Add("action", "General"); | |
| break; | |
| } | |
| } | |
| // Pass exception details to the target error View. | |
| routeData.Values.Add("error", exception); | |
| // Clear the error on server. | |
| Server.ClearError(); | |
| // Avoid IIS7 getting in the middle | |
| Response.TrySkipIisCustomErrors = true; | |
| // Call target Controller and pass the routeData. | |
| IController errorController = new ErrorController(); | |
| errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData)); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment