Exception handling in the "ASP. NET Web API tutorial" 4.3 ASP.

Source: Internet
Author: User

Reference page:

Http://www.yuanjiaocheng.net/webapi/create-crud-api-1-delete.html

Http://www.yuanjiaocheng.net/webapi/Consume-web-api.html

Http://www.yuanjiaocheng.net/webapi/mvc-consume-webapi-get.html

Http://www.yuanjiaocheng.net/webapi/mvc-consume-webapi-post.html

Http://www.yuanjiaocheng.net/webapi/mvc-consume-webapi-put.html

Note: This article is part of the ASP. NET Web API Series tutorial, if this is the first time you've seen this series of tutorials, look at the previous section first.

Exception Handling in ASP Web API
Exception handling in the ASP. NET Web API

This article quoted: http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling

by Mike Wasson | March 12, 2012
Mike Wasson | date: 2012-3-12

This article describes the error and exception handling in the ASP. NET Web API.
This article describes error and exception handling in the ASP. NET Web API:

    • Httpresponseexception
    • Exception Filters
      Exception filter
    • Registering Exception Filters
      Registering Exception Filters
    • Httperror
Httpresponseexception

What is happens if a Web API controller throws an uncaught exception? By default, the most exceptions is translated into a HTTP response with status code, Internal Server Error.
What happens if a Web API controller throws a non-catching exception? By default, most exceptions are converted to an HTTP response with the status code "500– Internal Server Error".

The httpresponseexception type is a special case. This exception returns any HTTP status code, specify in the exception constructor. For example, the following method returns 404, not Found, if the ID parameter are not valid.
The Httpresponseexception (HTTP response exception) type is a special case. 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 illegal, 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; }

For more control over the response, you can also construct the entire response a message and include it with the httprespons Eexception:
To take more control of the response, you can also construct the entire response message and include it with Httpresponseexception:

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 Httpresponseexcepti On (RESP);     }     return item; }
Exception Filters
Exception filter

Can customize how Web APIs handles exceptions by writing an exception filter. An exception filter was executed when a controller method throws any unhandled exception a Httpresponseexcepti On exception. The httpresponseexception type is a special case, because it was designed specifically for returning an HTTP response.
By writing an exception filter (exception filter), you can customize how the Web API handles exceptions. When a controller throws an unhandled exception with a non-httpresponseexception exception, an exception filter is executed. The httpresponseexception type is a special case because it is specifically designed to return an HTTP response.

Exception filters implement the System.Web.Http.Filters.IExceptionFilter interface. The simplest-to-write exception filter is to derive from the System.Web.Http.Filters.ExceptionFilterAttribute class and override the Onexception method.
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 ASP. NET Web API is similar to those in ASP. However, they is declared in a separate namespace and function separately. In particular, the Handleerrorattribute class used on MVC does not handle exceptions thrown by Web API controllers.
Exception filters in the ASP. NET Web API are simpler than ASP. However, the two are declared in different namespaces and are functionally independent. In particular, the Handleerrorattribute class used in MVC does not handle exceptions thrown in the Web API controller.

Here is a filter this converts notimplementedexception exceptions into the HTTP status code 501, not implemented:
The following is a filter that converts an NotImplementedException exception to an HTTP status code of "501-Not implemented":

Namespace Productstore.filters {     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 tha t be is sent to the client.
The Response property of the Httpactionexecutedcontext object contains the HTTP response message that will be sent to the client.

Registering Exception Filters
Registering Exception Filters

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

    • by action
      Register by Action
    • by controller
      Registered by controller
    • Globally
      Global Registration

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

    [Notimplexceptionfilter]public contact    getcontact (int id)     {         throw new NotImplementedException ("This method was not implemented");     } }

To apply the filter to any of the actions on a controller, add the filter as an attribute to the Controller class:
To apply the filter to all actions of a controller, add the filter's annotation properties to the controller:

public class productscontroller:apicontroller{    //...}

To apply the filter globally to all Web API controllers, add a instance of the filter to the globalconfiguration.conf Iguration. Filters Collection. Exeption filters in this collection the apply to any WEB API controller action.
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 use the "ASP. NET MVC 4 Web Application" project template to create your project, put your Web API configuration cod E inside the Webapiconfig class, which is located in the App_start folder:
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)                      // Other config code (other configuration codes) ...     } }
Httperror

The httperror object provides a consistent the return error information in the response body. The following example shows how to return HTTP status code 404 (Not Found) with a httperror in the response body :
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);             }     else     {         return request.createresponse (Httpstatuscode.ok, item);}     }

In this example, if the method was successful, it returns the product in the HTTP response. But if the requested product was not found, the HTTP response contains a httperror in the request body. The response might look like the following:
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 Found Content-type:application/json;  Charset=utf-8 Date:thu, 23:27:18 GMT content-length:51  {   "Message": "Product with id = no found" }

Notice that the httperror is serialized to JSON with this example. One advantage of using Httperror is that it goes through the same content-negotiation and serialization process a s any other strongly-typed model.
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" (Section 6.2 of this series tutorial-translator note) and serialization process is performed.

Instead of creating the httperror object directly, you can use the createerrorresponse method:
One way to override the direct creation of Httperror objects 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 a extension method defined in the System.Net.Http.HttpRequestMessageExtensions class. Internally, Createerrorresponse creates an httperror instance and then creates an Httpresponsemessage that contains the httperror.
Createerrorresponse is an extension method defined in the System.Net.Http.HttpRequestMessageExtensions class. Essentially,Createerrorresponse creates a httperror instance, and then creates a httperror that contains the Httpresponsemessage.

Httperror and Model Validation
Httperror and model validation

For model validation, you can pass the model state to Createerrorresponse, to include the validation errors in The response:
For model validation, you can pass the model state to Createerrorresponseto include validation errors in the response:

Public httpresponsemessage postproduct (Product item) {     if (! Modelstate.isvalid)     {         return request.createerrorresponse (Httpstatuscode.badrequest, modelstate);     }      Implementation not shown (Implementation code not listed) ...}

This example might return the following response:
This example may return the following response:

http/1.1-Bad Request Content-type:application/json; Charset=utf-8 content-length:320  {   "Message": "The request is invalid.",   "Modelstate": {     "item": [       "Required property ' Name ' isn't found in JSON. Path ", line 1, position."     ],     "item. Name ": [       " The Name field is required. "     ],     " item. Price ": [       " The field price must is between 0 and 999 "     ]   }}

For more information on the model validation, see Model Validation in ASP.
For more information about model validation, see "Model Validation in ASP." (Section 6.4 of this series of tutorials-the translator's note).

Adding Custom key-values to Httperror
Add a custom key-value to Httperror

The Httperror class is actually a Key-value collection (it derives from dictionary<string, object> ), so can add your own Key-value pairs:
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
Use Httpresponseexception to Httperror

The previous examples return a httpresponsemessage message from the controller action, but can also use Httpresponseexception to return an httperror. This lets return a strongly-typed model in the normal success case, while still returning httperror if there was an err Or
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;     }}

Read this article if you feel something rewarding, please give a recommendation

Exception handling in the "ASP. NET Web API tutorial" 4.3 ASP.

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.