ASP. 2 Seventh lesson--web API exception handling

Source: Internet
Author: User

Objective

Before reading this article, you can also go to the ASP. NET Web API 2 series navigation to view http://www.cnblogs.com/aehyok/p/3446289.html

This article focuses on the handling of errors and exceptions in the ASP. NET Web API, including the following:

1.httpresponseexception--http Response exception

2.Exception filters--anomaly Filter

3.Registering Exception filters--Register exception filter

4.httperror--http Error

Httpresponseexception--http Response exception

What happens if a Web API controller throws an uncaught exception? By default, most exceptions are converted to an HTTP response with an internal server error with status code 500.

This httpresponseexception type is a special type. This exception returns any HTTP status codes that you specify in the exception constructor. For example, in the following method, if the ID parameter is not valid, it returns "404--not found".

Public Product getproduct (int id) {     product item = Repository. Get (ID);     if (item = = null)     {         throw new httpresponseexception (Httpstatuscode.notfound);     }     return item; }

In order to have more control over the response, you can also construct the entire response message and use Httpresponseexception to include it:

Public Product getproduct (int id) {     product item = Repository. Get (ID);     if (item = = null)     {         var resp = new Httpresponsemessage (httpstatuscode.notfound)         {             Content = new Stringcontent (String. Format ("No product with id = {0}", ID),             reasonphrase = "Product ID not Found"         }         throw new httpresponseexcept Ion (RESP);     }     return item;

Exception filters--anomaly Filter

By writing an exception filter, you can customize how the Web API handles exceptions. When a controller throws an unhandled exception, and the exception is not a Httpresponseexception exception, an exception filter is executed. The httpresponseexception type is a special case because it is specifically designed to return an HTTP response.

The exception filter implements the System.Web.Http.Filters.IExceptionFilter interface. The simplest way to write an exception filter is to derive from the System.Web.Http.Filters.ExceptionFilterAttribute class and override its Onexception method.

Exception filters in the ASP. NET MVC are very similar to ASP. They are then declared in different namespaces, and the functionality is also independent. In particular, the Handleerrorattribute class used in ASP. NET MVC does not handle exceptions thrown in the Web API controller.

The following is a filter that converts an NotImplementedException exception to an HTTP status code of "501-Not implemented":

    Using System;     Using System.Net;     Using System.Net.Http;     Using System.Web.Http.Filters;      public class Notimplexceptionfilterattribute:exceptionfilterattribute      {public         override void Onexception ( Httpactionexecutedcontext context)         {             if (context. Exception is NotImplementedException)             {                 context. Response = new Httpresponsemessage (httpstatuscode.notimplemented);             }         }     

The Response property of the Httpactionexecutedcontext object contains the HTTP response message that will be sent to the client.

Registering Exception filters--Register exception filter

Here are a few ways to register the Web API exception filter:

    1. Registering with an action
    2. Registering via the Controller
    3. Global Registration

To apply a filter to a specific action, add the filter's annotation properties to the action:

public class Productscontroller:apicontroller {     [notimplexceptionfilter] public contact    getcontact (int id)     {         throw new NotImplementedException ("This method was not implemented");}     }

To apply the filter to all actions of a controller, add the filter's annotation properties to the controller:

[Notimplexceptionfilter] public class productscontroller:apicontroller{    //...}

To globally apply the filter to all Web API controllers, add an instance of the filter to the GlobalConfiguration.Configuration.Filters collection. The exception filter in this collection is applied to any Web API controller action.

GLOBALCONFIGURATION.CONFIGURATION.FILTERS.ADD (    new Productstore.notimplexceptionfilterattribute ());

If you are using a project created by the ASP. NET MVC 4 Web application project template, put your Web API configuration code in the Webapiconfig class, which is located in the App_start folder:

public static class Webapiconfig {public     static void Register (httpconfiguration config)     {         config. Filters.add (New Productstore.notimplexceptionfilterattribute ());          Other config code (other configuration codes) ...     } }

Httperror--http Error

The httperror object provides an appropriate way to return an error message in the response body. The following example shows how to return the HTTP status code "404-Not Found" in the response body with Httperror :

Public httpresponsemessage getproduct (int id) {     Product item = Repository. Get (ID);     if (item = = null)     {        var message = string. Format ("Product with id = {0} not found", id);         Httperror err = new Httperror (message);         Return Request.createresponse (Httpstatuscode.notfound, err);     }     else     {         return request.createresponse (Httpstatuscode.ok, item);}     }

In this example, if the method succeeds, it returns the product in the HTTP response. However, if the requested product is not found, the HTTP response contains a httperrorin the request body. The response looks roughly like this:

http/1.1 404 Not Foundcontent-type:application/json; Charset=utf-8date:thu, 23:27:18 gmtcontent-length:51{  "Message": "Product with id = no found"}

Note that in this example,httperror is serialized into JSON. One advantage of using Httperror is that, as with other strongly typed models, the same "Content-negotiation" (pending) and serialization processes are performed.

One way to directly override the creation of a Httperror object is that you can use the createerrorresponse method:

Public httpresponsemessage getproduct (int id) {     Product item = Repository. Get (ID);     if (item = = null)     {         var message = string. Format ("Product with id = {0} not found", id);         Return Request.createerrorresponse (httpstatuscode.notfound, message);     }     else     {         return request.createresponse (Httpstatuscode.ok, item);}     }

createerrorresponse is defined as an extension method in the System.Net.Http.HttpRequestMessageExtensions class. Essentially,Createerrorresponse creates an httperror instance and then creates a httpresponsemessage that contains the httperror . .

Adding Custom Key-values to httperror add the customized key value to the Httperror

The Httperror class is actually a "key-value" collection (it derives from dictionary<string, object>), so you can add your own "key-value" pairs:

Public httpresponsemessage getproduct (int id) {     Product item = Repository. Get (ID);      if (item = = null)     {         var message = string. Format ("Product with id = {0} not found", id);         var err = new Httperror (message);         err["Error_sub_code"] =;         Return Request.createerrorresponse (Httpstatuscode.notfound, err);     }     else     {         return request.createresponse (Httpstatuscode.ok, item);}     }

Using Httperror with httpresponseexception in Httpresponseexception way Httperror

The previous example returns a httpresponsemessage message from the controller action, but you can also use httpresponseexception to return a httperror. This allows you to return a strongly typed model in a normal success condition, but still returns Httperrorif there is an error.

Public Product getproduct (int id) {     product item = Repository. Get (ID);     if (item = = null)     {         var message = string. Format ("Product with id = {0} not found", id);         throw new Httpresponseexception (             request.createerrorresponse (httpstatuscode.notfound, message));     }     else     {         return item;     }}

Summarize

It feels better than exception handling in MVC and does not know what the exception handling mechanism is in the new version of MVC. The next article will explain in the future Web API2 a new highlight mechanism ———— attribute routing, seemingly very good appearance.

ASP 2 Seventh lesson--web API exception handling

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.