"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 any of the following values:
1, void
2, Httpresponsemessage
3, Ihttpactionresult
4, Some other type

Depending on which of these returns, the Web API uses a different mechanism to create the HTTP response.

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 describes each of the return values in detail.

void

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

Example controller:

publicclass ValuesController : ApiController{    publicvoidPost()    {    }}

HTTP corresponds to:

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

If an action returns the Httpresponsemessage,web API, it is constructed as a message via the Httpresponsemessage property to directly convert the return value into 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

If you pass a domain model to the Createresponse method, the Web API writes the serialization model to the response body using Media Format (medium formatter).

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 benefits of using the Ihttpactionresult interface:
1, simple unit test of your controller
2, move public logic to a separate class for creating HTTP accordingly
3. Make the controller move clearer by hiding the underlying details

Ihttpactionresult contains a separate method, Executeasync, that asynchronously creates an Httpresponsemessage instance:

publicinterface IHttpActionResult{    

If a controller action returns the Ihttpactionresult,web API, the Executeasync method is called to create the httpresponsemessage. The httpresponsemessage is then converted to the HTTP corresponding message.

The following is a simple execution of a ihttpactionresult, which creates a text corresponding to:

 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:

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 example, if the request does not match any existing product ID, the controller calls Apicontroller.notfound to create a 404 (not Found) response. Otherwise, the controller calls Apicontroller.ok, which invokes a corresponding (OK) containing 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 Format (medium 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, such as 404.

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

Sample Request:

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

The 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

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.