Global exception Handling in ASP. NET Core Webapi

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.