Just add the following code to the Global.asax file, you can display the error page friendly after an error, and you don't need to write code that logs the error log in many places
protected voidApplication_Error (Objectsender, EventArgs e) { if(HttpContext.Current.IsCustomErrorEnabled) {return; } varException =Server.GetLastError (); varHttpException =NewHttpException (NULL, exception); //Logging error Logs if(Httpexception.innerexception! =NULL) {Logmanager.writerlog (httpException.InnerException.ToString (), DateTime.Now.ToString ("YYYYMMDD")); } varRoutedata =NewRoutedata (); ROUTEDATA.VALUES.ADD ("Controller","Error"); ROUTEDATA.VALUES.ADD ("Action","Index"); ROUTEDATA.VALUES.ADD ("HttpException", HttpException); Server.ClearError (); varErrorcontroller =ControllerBuilder.Current.GetControllerFactory (). Createcontroller (NewRequestContext (NewHttpcontextwrapper (Context), Routedata),"Error"); Errorcontroller.execute (NewRequestContext (NewHttpcontextwrapper (Context), routedata)); }
Logmanager.writerlog is a log record class that I wrote on my own, which simply records the wrong things.
Public classLogmanager {/// <summary> ///Logging error Logs/// </summary> /// <param name= "Content" >Error Content</param> /// <param name= "FileName" >file name</param> Public Static voidWriterlog (stringContentstringfileName) { varPath = Httpruntime.appdomainapppath +"\\Log\\"+ DateTime.Now.ToString ("yyyy-mm") +"\\"; if(!directory.exists (path)) {directory.createdirectory (path); } fileName= path + FileName +". txt"; if(!file.exists (FileName)) {file.create (fileName). Dispose (); } using(varSW =File.appendtext (FileName)) {SW. WriteLine (DateTime.Now); Sw. WriteLine (content); Sw. WriteLine (""); } } }
At the time of publishing to the server, we can also copy the project's. pdb files in the past, so that when logging the error log, the line number and the path of the error file is also recorded, more convenient to locate and repair.
ASP. NET MVC custom error page and logs the error log