C # Advanced Series--webapi Exception handling solution

Source: Internet
Author: User

Source: http://www.cnblogs.com/landeanfen/p/5363846.html

Read Catalogue

    • One, catch all exceptions using exception filters
    • Second, httpresponseexception custom exception information
    • Iii. return to Httperror
    • Iv. Summary

Body

Preface: The previous C # Advanced Series--webapi interface is no longer confused: the transfer of parameters is introduced in detail, this article looks at the handling of WEBAPI inside the exception. Regarding exception handling, we are certainly not unfamiliar as programmers, remember when introducing AOP, we have said that through AOP can be unified interception of exceptions. So in our webapi is generally how to deal with the exception, today this one, Bo master with everyone to practice under the Webapi of exception handling.

WEBAPI Series Articles

    • C # Advanced Series--webapi Interface test tool: Webapitestclient
    • C # Advanced Series--webapi cross-domain problem solution: CORS
    • C # Advanced Series--webapi Identity Authentication solution: Basic BASIC Certification
    • C # Advanced Series--WEBAPI Interface transfer parameter no longer confused: The explanation of the transfer parameter
    • C # Advanced Series--webapi interface return value not confused: return value type detailed
    • C # Advanced Series--webapi Exception handling solution
    • C # Advanced Series--webapi Regional Area usage Summary

Why is that practice? Because the exception handling mechanism of WEBAPI has been explicitly given in http://www.asp.net. Theory is not enough, let's try it today. Through practice, we may find some more detailed usage.

Back to top one, catch all exceptions using exception filters

We know that in general, WEBAPI is used as a service, each time the client sends an HTTP request to our WEBAPI service, the server gets the result output response to the client. In this process, once an exception occurs on the server, a 500 error is returned to the client uniformly.

        [HttpGet]        public string Getallchargingdata ([fromuri]tb_charging obj)        {            throw new NotImplementedException ("Method not supported");        }

Let's take a look at the HTTP request

And sometimes, we need to get more accurate error code to determine the type of exception, how to do?

Remember when introducing AOP, we introduced the Iexceptionfilter interface in MVC, which is used to define the methods required by the exception filter, and in Webapi, there is an exception filter, and below we have an example to see how to implement.

First create a new class WebApiExceptionFilterAttribute.cs in App_start, inherit Exceptionfilterattribute, override Onexception method

Press CTRL + C to copy the code<textarea></textarea>Press CTRL + C to copy the code

Code parsing: by judging the specific type of exception, to return different HTTP status code to the client, the sample written two, according to the actual situation of the project to add some specific we want to catch the exception, and then write the corresponding status code to the HTTP request response inside, For some exceptions where we cannot judge the type, we return the service-side error 500 uniformly. about HTTP status codes, the framework defines some common types, and we'll look at:

HTTP status Code

The exception handling method is defined, and the rest is how to use it. A unified exception handling mechanism can be used at different levels, depending on the actual situation.

1. Interface level
        [Webapiexceptionfilter]        [HttpGet]        public string Getallchargingdata ([fromuri]tb_charging obj)        {            throw new NotImplementedException ("Method not supported");        }

After the exception is executed, it is advanced to the Onexception method:

After execution is done, the browser views:

if necessary, you can even write a custom description to the status code, and you can write the information we want to our response content . Let's change the Onexception method a little bit:

if (Actionexecutedcontext.exception is notimplementedexception)            {                var oresponse = new Httpresponsemessage ( httpstatuscode.notimplemented);                Oresponse.content = new Stringcontent ("Method not supported");                Oresponse.reasonphrase = "This Func was not supported";                Actionexecutedcontext.response = Oresponse;            }

Look at Reasonphrase description information

Look at response's descriptive information.

2. Controller level

If you want all the interfaces in one or more controllers to use exception filtering, label the features directly on the controller.

    • Enable exception filtering on one controller
[Webapiexceptionfilter]    public class Chargingcontroller:baseapicontroller    {        #region Get        [httpget] public        string Getallchargingdata ([fromuri]tb_charging obj)        {            throw new NotImplementedException ("Method not Supported");}    }
    • Multiple controllers enable exception filtering at the same time
    [Webapiexceptionfilter]    public class Baseapicontroller:apicontroller    {    }
    public class Chargingcontroller:baseapicontroller    {        #region Get        [httpget] public        string Getallchargingdata ([fromuri]tb_charging obj)        {            throw new NotImplementedException ("Method not Supported");}    }

This allows exception filtering to be enabled for all subclasses that inherit Baseapicontroller.

3. Global configuration

If you need to enable exception filtering for the entire application, you need to do the following two steps:

1, add GlobalConfiguration.Configuration.Filters.Add (New Webapiexceptionfilterattribute ()) in Global.asax global configuration; This sentence is as follows:

void Application_Start (object sender, EventArgs e)        {            //code to run at application startup            Arearegistration.registerallareas ();            Globalconfiguration.configure (webapiconfig.register);            Routeconfig.registerroutes (routetable.routes);            GLOBALCONFIGURATION.CONFIGURATION.FILTERS.ADD (New Webapiexceptionfilterattribute ());        }

2. Add config to the Register method of the WebApiConfig.cs file . Filters.add (New Webapiexceptionfilterattribute ()); This sentence is as follows:

        public static void Register (httpconfiguration config)        {            //cross-domain Configuration            config. Enablecors (New Enablecorsattribute ("*", "*", "*"));            Web API Routing            config. Maphttpattributeroutes ();            RouteTable.Routes.MapHttpRoute (                name: "Defaultapi",                routetemplate: "Api/{controller}/{action}/{id}",                defaults:new {id = routeparameter.optional}            ). Routehandler = new Sessioncontrollerroutehandler ();            Config. Filters.add (New Webapiexceptionfilterattribute ());        }
Back to top two, httpresponseexception custom exception information

This is the global exception capture and processing, in some cases we want to send the information to the client in an unusual way, we may need to use our httpresponseexception. Like what:

        [HttpGet]        Public tb_charging GetById (string id)        {            //query entity            var Omodel = server from the background. Find (ID);            if (Omodel = = null)            {                var resp = new Httpresponsemessage (httpstatuscode.notfound)                {                    Content = new Stringcontent (String. Format ("No object found for id={0}", id),                    reasonphrase = "object is not found"                };                throw new Httpresponseexception (RESP);            }            return omodel;        }

After executing the browser to view the results:

Code Explanation: The careful friend May, discovered, here both uses the Httpresponsemessage, but also uses the httpresponseexception, then, like this controllable anomaly, Can we directly return to the client in the form of httpresponsemessage without throwing an exception? Here is the difference between the two objects, the blogger's understanding is that the Httpresonsemessage object is used to respond to the message and contains the status code and data content, thehttpresponseexception object is used to return the exception containing the error message to the client.

Read an article on the Internet to describe the difference between the two: when the Web API service is called when a different error occurred, it should be expected to abort the program to return an error message, the return of the error is to use Httpresponseexception, and the use of Httpresponsemessage means that when a client sends a work request and the Web API completes the work correctly, it can use Httpresponsemessage to return a 201 message, so Httpresponsemessage and Httpresponseexception in the use of the fundamental goal is different, with Httpresponsemessage to return an exception error will also make the program structure is difficult to identify and not clear.

Back to top three, return to Httperror

The Httperror object provides a consistent way to respond to the message that returns an error in the body. To be exact, Httperror is not an exception, but an object used to wrap the error message. in fact, to a certain extent, httperror and httpresponsemessage use more similar, both can return the HTTP status code and error messages to the client, And can be included in the Httpresponseexception object to send back to the client. However, in general, Httperror is used only when an error message is returned to the client, and the Httpresponsemessage object can either return an error message or return a request for the correct message . In fact, there is nothing particularly good about httperror, let's look at an example to understand:

Public httpresponsemessage Update (Dynamic obj)        {            tb_product omodel = null;            Try            {                var id = convert.tostring (obj.id);                Omodel = newtonsoft.json.jsonconvert.deserializeobject<tb_product> (convert.tostring (Obj.dataModel));                //... Complex business logic            }            catch (Exception ex)            {                return request.createerrorresponse (Httpstatuscode.badrequest, ex . Message);            }            Return request.createresponse<tb_product> (Httpstatuscode.ok, Omodel);        }

If an exception occurs while executing the complex business logic in the try, we catch the exception and return the Httperror object to the client, which contains our custom error message and returns the Httpresponsemessage object if it is normal.

If the request exception:

If the request is normal

Back to top four, summary

The above three kinds of abnormal processing methods, can be used according to different scenarios.

    • If the project does not require a high level of exception handling, just record the Exception log, then use the exception filter to get it done
    • If the project requires a different exception, the client does different processing. This time using exception filters does not detail all the exceptions, possibly using the Httpresponseexception object is a better choice, defining finer exceptions and exception descriptions.
    • For when to use Httperror, and when to use Httpresponsemessage, you can refer to the above three usage.
    • Of course, the actual project is likely to be used in both or three of these.

The following is a few simple examples of the WEBAPI inside the exception of the processing mechanism, may not be deep enough, but for the general project exception handling basic enough. In fact, there is a point that bloggers have not yet figured out how to uniformly capture the exceptions inside the constructor. Through the exception filter is not captured, do not know the garden friends have any better way, generous enlighten, thank you! If this article can help you, may wish to recommend , your recommendation is Bo Master continue to summarize the power!

C # Advanced Series--webapi Exception handling solution (GO)

Related Article

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.