"Web API Series tutorial" 1.2-web action Results in API 2

Source: Internet
Author: User

Preface

The topic in this section is how the ASP. NET Web API converts the return value of a controller action into an HTTP response message.

The WEB API controller action can return the following values regardless of value:
1. void
2. Httpresponsemessage
3, Ihttpactionresult
4, Some other type

Depends on which of the above returns. The Web API uses different mechanisms to create HTTP responses.

How
Return TypeWeb API creates the response
void Return Empty 204 (No Content)
Httpresponsemessage Convert directly to an HTTP response message.
Ihttpactionresult Call Executeasync to create a httpresponsemessage, then convert to an HTTP response message.
Other type Write the serialized return value into the response body; Return (OK).

The remainder of this section will describe each of the return values in detail.

void

Assuming that the return type is Type,web API will return an empty HTTP response with the status Code 204 (No Content).

Demo Sample Controller:

publicclass ValuesController : ApiController{    publicvoidPost()    {    }}

HTTP Correspondence:

HTTP/1.1 204 No ContentServerMicrosoft-IIS/8.0DateMon, 27 Jan 2014 02:13:26 GMT
Httpresponsemessage

Suppose an action returns a Httpresponsemessage,web API that is constructed as a message via the Httpresponsemessage property to directly convert the return value to an HTTP response.

publicclass ValuesController : ApiController{    publicGet()    {        "value");        new StringContent("hello", Encoding.Unicode);        new CacheControlHeaderValue()        {            MaxAge = TimeSpan.FromMinutes(20)        };        return response;    } }

Corresponding:

HTTP/1.1 200 OKCache-Controlmax-age=1200Content-Length10Content-Typetext/plain; charset=utf-16ServerMicrosoft-IIS/8.0DateMon, 27 Jan 2014 08:53:35 GMThello

Assume that a domain model is passed to the Createresponse method. The Web API uses media formatter to write the serialized model to the response body.

publicGet(){    // Get a list of products from a database.    IEnumerable<Product> products = GetProductsFromDB();    // Write the list to the response body.    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, products);    return response;}
Ihttpactionresult

The Ihttpactionresult interface was introduced in Web API 2. Essentially, it defines a httpresponsemessage factory. The following are the advantages of using the Ihttpactionresult interface:
1, simple unit test of your controller
2. Move public logic to a separate class for creating HTTP correspondence
3. Build the underlying details by hiding it. Make the controller move more clearly

The Ihttpactionresult includes a separate method Executeasync. It asynchronously creates an Httpresponsemessage instance:

publicinterface IHttpActionResult{    

Assuming a controller action returns the Ihttpactionresult,web API calls the Executeasync method to create the httpresponsemessage. The httpresponsemessage is then converted into an HTTP corresponding message.

Here is a simple run of ihttpactionresult, which creates a text counterpart:

 Public classtextresult:ihttpactionresult{string_value; Httprequestmessage _request; Public Textresult(string value, Httprequestmessage request) {_value =value;    _request = Request; } PublicTaskExecuteasync(CancellationToken CancellationToken) {varResponse =NewHttpresponsemessage () {Content =NewStringcontent (_value), requestmessage = _request};returnTask.fromresult (response); }}

Example of a controller action demo:

publicclass ValuesController : ApiController{    publicGet()    {        returnnew TextResult("hello", Request);    }}

Corresponding:

HTTP/1.1 200 OKContent-Length5Content-Typetext/plain; charset=utf-8ServerMicrosoft-IIS/8.0DateMon, 27 Jan 2014 08:53:35 GMThello

More generally, you will use the Ihttpactionresult implementation defined under the System.Web.Http.Results namespace.

In the next demo sample, assume that the request does not match the product ID regardless of what already exists. The controller calls Apicontroller.notfound to create a 404 (not Found) response. Otherwise, the controller calls Apicontroller.ok, which invokes a (OK) correspondence that means including the product.

publicGet (int id){    Product product = _repository.Get (id);    ifnull)    {        return// Returns a NotFoundResult    }    return Ok(product);  // Returns an OkNegotiatedContentResult}
Other Return Types

For all other return types. The Web API uses media formatter to serialize the return value.

The Web API writes serialized values to the response body. The response status code is (OK).

publicclass ProductsController : ApiController{    publicGet()    {        return GetAllProductsFromDB();    }}

The disadvantage of this implementation is that you cannot directly return an error code, for example 404.

The Web API chooses the format by using the Accept header in the request.

Demo Sample Request:

GET http://localhost/api/products HTTP/1.1User-AgentFiddlerHostlocalhost:24127Acceptapplication/json

The demo sample corresponds to:

http/1.1 200  OK  content-type : application/json; charset=utf-8  Span class= "Hljs-attribute" >server : microsoft-iis/8.0  date : mon, Jan 08:53:35 GMT  content-length : 56  [{" Span class= "Hljs-attribute" >id  ": 1  ," Span class= "Hljs-attribute" >name ": " yo-yo " , "category ":  ," price  ":  6.95  }]  

Web API Series Tutorial 1.2-web action Results

in API 2

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.