Through the global exception class, all errors encountered in the program are intercepted and the results are returned amicably.
1. Customizing a global exception handling class middleware
usingMicrosoft.AspNetCore.Http;usingNewtonsoft.json;usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Net;usingSystem.Threading.Tasks;usingSystem.Xml.Serialization;usingUFX. Mall.entitymodel;usingUFX. Tools;namespaceUFX. mall.webapi{ Public classExceptionhandlermiddleware {Private ReadOnlyrequestdelegate Next; PublicExceptionhandlermiddleware (requestdelegate next) { This. Next =Next; } Public AsyncTask Invoke (HttpContext context) {Try { awaitNext (context); } Catch(Exception ex) {awaitHandleexceptionasync (context, ex); } } Private Static AsyncTask Handleexceptionasync (HttpContext context, Exception Exception) {if(Exception = =NULL)return; awaitWriteexceptionasync (context, exception). Configureawait (false); } Private Static AsyncTask Writeexceptionasync (HttpContext context, Exception Exception) {//Record LogLoghelper.error (Exception. GetBaseException (). ToString ()); //back to Friendly tips varResponse =context. Response; //Status Code if(Exception isunauthorizedaccessexception) Response. StatusCode= (int) httpstatuscode.unauthorized; Else if(Exception isException) Response. StatusCode= (int) Httpstatuscode.badrequest; Response. ContentType= Context. request.headers["Accept"]; if(Response. Contenttype.tolower () = ="Application/xml") { awaitResponse. WriteAsync (object2xmlstring (Resultmsg.failure (exception. GetBaseException (). Message)). Configureawait (false); } Else{Response. ContentType="Application/json"; awaitResponse. WriteAsync (Jsonconvert.serializeobject (Resultmsg.failure (exception. GetBaseException (). Message)). Configureawait (false); } } /// <summary> ///object to XML/// </summary> /// <param name= "O" ></param> /// <returns></returns> Private Static stringObject2xmlstring (Objecto) {stringwriter SW=NewStringWriter (); Try{XmlSerializer Serializer=NewXmlSerializer (O.gettype ()); Serializer. Serialize (SW, O); } Catch { //Handle Exception Code } finally{SW. Dispose (); } returnSW. ToString (); } }}
The return value is formatted by default into a custom class resultmsg, which returns a custom entity based on its own project requirements
It is automatically converted to XML or JSON according to the format required by the client.
2, configure registration
//This method gets called by the runtime. Use this method to configure the HTTP request pipeline Public voidConfigure (Iapplicationbuilder app, Ihostingenvironment env, iloggerfactory loggerfactory) {Loggerf Actory. Addconsole (Configuration.getsection ("Logging")); Loggerfactory.adddebug (); //Configure NlogLoggerfactory.addnlog (); Env. Configurenlog ("Nlog.config"); App. Useapplicationinsightsrequesttelemetry (); App. Useapplicationinsightsexceptiontelemetry (); //Exception Handling Middleware app. Usemiddleware (typeof (Exceptionhandlermiddleware)); App. Usemvc (); }
3, call off, all exceptions can be processed
ASP. NET Core WEBAPI Global Exception class