In. NET core, MVC and WEBAPI have been combined to inherit the controller, but when it comes to handling errors, MVC returns an error page to the browser, WEBAPI returns JSON or XML instead of HTML. Useexceptionhandler Middleware can handle global exceptions
App. Useexceptionhandler (Options =>{ options. Run (Async context = { context. Response.statuscode = (int) httpstatuscode.internalservererror; Context. Response.ContentType = "Application/json"; var ex = context. Features.get<iexceptionhandlerfeature> (); if (ex! = null) { //todo custom response structure Consistency string text = Jsonconvert.serializeobject (new { message = ex. Error.message }); Await the context. Response.writeasync (text);}); });
Open ValuesController.cs, modify code, manually throw an exception
[Httpget]public ienumerable<string> Get () { int a= 1; int b = a/0; return new string[] {"value1", "value2"};}
Run the application you should be able to see
Another way is to use Iexceptionfilter
public class customexceptionfilter:microsoft.aspnetcore.mvc.filters.iexceptionfilter{public void Onexception ( Exceptioncontext context) { context. HttpContext.Response.StatusCode = (int) httpstatuscode.internalservererror; Context. HttpContext.Response.ContentType = "Application/json"; var ex = context. Exception; if (ex! = null) { //todo custom response structure Consistency string text = Jsonconvert.serializeobject (new { message = ex. Message }); Context. HttpContext.Response.WriteAsync (text);}} }
Finally, add our filters in the Startup.cs configureservices method
public void Configureservices (iservicecollection services) { services. ADDMVC (options = options. Filters.add (typeof (Customexceptionfilter));} );
In this article we use built-in middleware and built-in exception filters to handle exceptions.
Global exception Handling in ASP. NET Core Webapi