Asp. Net Web API (IV), asp. netwebapi

Source: Internet
Author: User

Asp. Net Web API (IV), asp. netwebapi
HttpResponseException ----- HTTP Response exception

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

The HTTPResponseException type is a special type. This exception will return any HTTP status code you specified in the exception constructor. For example, in the following method, if this id parameter is invalid, "404 --- not found" is returned"

1 public Product GetProduct (int id) 2 {3 var item = repository. get (id); 4 if (item = null) 5 // a 404 Status Code 6 throw new HttpResponseException (HttpStatusCode. notFound); 7 return item; 8}

To control the response, you can also construct the entire response message and use HTTPResponseMessage to include it:

1 public Product GetProduct (int id) 2 {3 var item = repository. get (id); 4 if (item = null) 5 // a 404 Status Code 6 {7 var resp = new HttpResponseMessage (HttpStatusCode. notFound) 8 {9 Content = new StringContent (String. format ("No product with ID = {0}", id), 10 ReasonPhrase = "Product ID Not Found" 11}; 12 throw new HttpResponseException (resp ); 13} 14 return item; 15}
Exception Filters --- Exception filter

By writing an exception filter, you can customize how the Web API handles exceptions. When a controller throws an unprocessed exception that is not an HttpResponseException, an exception filter is executed. The HttpResponseException type is a special case because it is specially designed to return an HTTP response.

Exception Filter ImplementationSystem. Web. Http. Filters. IExceptionFilterInterface. The simplest way to write an exception filter is to useSystem. Web. Fitlers. ExceptionFilterAttributeClass, and rewriteOnExceptionMethod.

Note: exception filters in ASP. NET Web APIs are similar to those in ASP. net mvc. Then, they are declared in a namespace that is not used, and their functions are independent. Special emphasis on the following:HandlerErrorFilterAttributeDoes not handle exceptions thrown by the Web API controller.

The following filters convert NotImplementedException exceptions to HTTP status code 501-not implemented:

 1 namespace WebAPIDemo.Filter 2 { 3     public class NotImpleExceptionFilterAttribute:ExceptionFilterAttribute 4     { 5         public override void OnException(HttpActionExecutedContext actionExecutedContext) 6         { 7             if (actionExecutedContext.Exception is NotImplementedException) 8                 actionExecutedContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.NotImplemented); 9         }10     }11 }

HttpActionExecutedContextObjectResponseThe property contains the HTTP Response Message sent to the client.

Registering Exception Filters --- register an Exception filter

The following are several methods to register a Web API exception filter:

1. register through Action

2. register through Controller

3. Use global registration

Apply the filter to a specific Action and add the annotation attribute of the filter to the Action.

1 [NotImpleExceptionFilter] 2 public Product GetProduct (int id) 3 {4 var item = repository. get (id); 5 if (item = null) 6 // a 404 status code 7 {8 var resp = new HttpResponseMessage (HttpStatusCode. notFound) 9 {10 Content = new StringContent (String. format ("No product with ID = {0}", id), 11 ReasonPhrase = "Product ID Not Found" 12}; 13 throw new HttpResponseException (resp ); 14} 15 return item; 16}

To apply the filter to all actions of a Controller, you can add the annotation attribute of the filter on the Controller.

[NotImpleExceptionFilter]public class ProductController : ApiController{
   
}

Apply the filter to all Web API controllers to add an instance of the filter globally.GlobalConfiguration. Configuration. Filter set. All the exception filters in this set are applied to any Web API controller Action.

Public class WebApiApplication: System. Web. HttpApplication {protected void Application_Start () {// register the global exception filter GlobalConfiguration. Configuration. Filters. Add (new NotImpleExceptionFilterAttribute ());}}

HttpError ---- HTTP Error

The HttpError object provides a response method for the error message returned in the response body. The following example demonstrates how to use HttpError to return the HTTP status code "404 -- not found" in the response ":

1 public HttpResponseMessage GetProduct(int id)2 {3             var item = repository.Get(id);4             if (item != null)5                 return Request.CreateResponse(HttpStatusCode.OK, item);6             var message = string.Format("Product with id = {0} not found", id);7             HttpError httpError = new HttpError(message);8             return Request.CreateResponse(HttpStatusCode.NotFound, httpError);9 }

In this example, if the method is successful, it will return the product in the HTTP response. However, if the requested product is not found, the HTTP response will contain an HttpError in the Request body. The response looks like this.

1 HTTP/1.1 404 Not Found2 Content-Type: application/json; charset=utf-83 Date: Thu, 09 Aug 2012 23:27:18 GMT4 Content-Length: 515 6 {7   "Message": "Product with id = 12 not found"8 }

Note. In this example, HttpError is serialized into JSON. One advantage of using HttpError is that, like other strong-type models, the same "content-negotiation" and sequence process will be performed (not implemented yet ).

One way to directly replace the HttpError object is: You can use the CreateErrorResponse method:

1 public HttpResponseMessage GetProduct(int id)2 {3             var item = repository.Get(id);4             if (item != null)5                 return Request.CreateResponse(HttpStatusCode.OK, item);6             var message = string.Format("Product with id = {0} not found", id);7             return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);8 }

CreateErrorResponseInSystem. Net. Http. HttpRequsetMessageExtensionsClass. Essentially,CreateErrorResponseCreatesHttpErrorInstance, and then createHttpResponseMessage of HttpError

Adding Custom Key-Values to HttpError Add the Custom Key value to HttpError

HttpErrorThe class is actually a key-value set (derived from Dictionary <String, Object>), so you can add your own key-Value Pair

 1 public HttpResponseMessage GetProduct(int id) 2 { 3             var item = repository.Get(id); 4             if (item != null) 5                 return Request.CreateResponse(HttpStatusCode.OK, item); 6             var message = string.Format("Product with id = {0} not found", id); 7             var err = new HttpError(message); 8             err["error_sub_code"] = 42; 9             return Request.CreateErrorResponse(HttpStatusCode.NotFound, err);10 }

 

Using HttpError with HttpResponseExceptionToHttpResponseExceptionTo useHttpError

In the preceding example, an HttpResponseMessage message is returned from the Action, but you can also use HttpResponseException to return an HttpError message. This allows you to return a strong-type model when the model is successful, and return HttpError in case of an error.

1 public Product GetProduct(int id)2 {3             var item = repository.Get(id);4             if (item != null)5                 return item;6             var message = string.Format("Product with id = {0} not found", id);7             throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, message));8 }

 

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.