Get start-How to convert the controller's return value to an HTTP response message

Source: Internet
Author: User

A Web API controller method can return the following types of values

1.void

2.HttpResponseMessage

3.IHttpActionResult

4. Some other types

Depending on the return type of the action, the Web API uses different processing methods to create an HTTP response message.

Action return type

Web API how to generate a response message

void

Return to empty 204 (No Content)

Httpresponsemessage

Convert directly to HTTP response message

Ihttpactionresult

Call the Executeasync method to create a Httpresponsemessage object that will then convert the object to an HTTP response message

Other types

Writes the serialized value to the contents of the response message, returning a maximum of (OK)

The following is a detailed description of each type of return

void

If the action returns a void type, the Web API returns an empty HTTP response message with the status code: 204 (No Content)

For example:

 Public class valuescontroller:apicontroller{    publicvoid  Post ()    {    }}

When you execute this action, the response message is:

http/1.1 204 No Contentserver:microsoft-iis/8.0date:mon, Jan 02:13:26 GMT

Httpresponsemessage

If the action returns a Httpresponsemessage type value, the Web API translates the object directly into an HTTP response message, using the property values of the Httpresponsemessage object to populate the response message.

The way to return the Httpresponsemessage type gives us more control over the ability to respond to messages, such as the following controller action implements the value of setting the response message header Cache-control

 Public classvaluescontroller:apicontroller{ Publichttpresponsemessage Get () {httpresponsemessage response= Request.createresponse (Httpstatuscode.ok,"value"); Response. Content=NewStringcontent ("Hello", Encoding.unicode); Response. Headers.cachecontrol=NewCachecontrolheadervalue () {MaxAge= Timespan.fromminutes ( -)        }; returnresponse; } }

Response message:

http/1.1 Okcache-control:max-age=1200content-length:10content-type:text/plain; Charset=utf-16server:microsoft-iis/8.0date:mon, 08:53:35 Gmthello

If you pass a model object (domain model) to the Createresponse method, the Web API serializes the object using media formatter and writes the serialized content to the response body content.

 Public Httpresponsemessage Get () {    //  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;}

As above, the Web API selects the format of the response message content using the format specified by the header of the request message (Implementation of the content negotiation)

Ihttpactionresult

The Ihttpactionresult interface is introduced in the Web API2, essentially, it is a httpresponsemessage factory (for example, using NotFound () can return a 404 response, Ok (products) can return a 200 responds to and returns the content, both of which have the Ihttpactionresult interface implemented for the type returned by the method.

There are several advantages to using the Ihttpactionresult interface:

--simplifies unit testing of the Controller

--Separating the primary logic for creating HTTP responses into different classes

--Make the intent of the controller action clearer by hiding the underlying details that create the response message.

Ihttpactionresult contains only one method, Executeasync, which can asynchronously create a Httpresponsemessage object.

 Public Interface ihttpactionresult{    Task<HttpResponseMessage> executeasync (cancellationtoken CancellationToken);}

If a controller method returns an Ihttpactionresult type Object, the Web API calls the Executeasync method to create a Httpresponsemessage object and then converts the object to an HTTP response message.

You can implement the Ihttpactionresult interface yourself, implementing a custom conversion method, such as returning a plain text type response message

 Public classtextresult:ihttpactionresult{string_value;    Httprequestmessage _request;  PublicTextresult (stringvalue, httprequestmessage request) {_value=value; _request=request; }     PublicTaskExecuteasync (CancellationToken cancellationtoken) {varResponse =NewHttpresponsemessage () {Content=Newstringcontent (_value), Requestmessage=_request}; returnTask.fromresult (response); }}

The Controller method writes like this:

 Public class valuescontroller:apicontroller{    public  ihttpactionresult Get ()    {         return New Textresult ("hello", Request);}    }

At this point the response message is:

http/1.1 Okcontent-length:5content-type:text/plain; Charset=utf-8server:microsoft-iis/8.0date:mon, 08:53:35 Gmthello

In general, you should define the implementation class for the Ihttpactionresult interface under the System.Web.Http.Results namespace, the Apicontoller class defines helper methods that Return these built-in action results. (The Apicontroller class defines a way to return (these built-in action return types) help information.

In the following example: If the product of the requested ID is not found, the controller calls Apicontroller.notfound to create a 404 (not Found) response message. Otherwise, the controller calls Apicontroller.ok and creates a response message with a (OK) containing the product volume information.

 Public Ihttpactionresult Get (int  ID) {    = _repository. Get (ID);     if NULL )    {        return//  Returns a notfoundresult    }     return Ok (product);  // Returns an Oknegotiatedcontentresult}

Other return types

For other action return types, the Web API uses media formatter to serialize the return value, and the Web API writes the serialized value to the body of the Shaw Response message with a response status code of (OK)

 Public class productscontroller:apicontroller{    public ienumerable<product> Get ()    {         return  getallproductsfromdb ();    }}

The action above returns a list type that, if the Accept header information is not specified in the request message (the type that requests the content of the response message), the list object is serialized to JSON (the default) and returned to the browser.

One drawback of returning other types is that you cannot directly return a response error code, such as 404, and of course, you can return a response error code by throwing a httpresponseexception exception, and more information can be viewed (Exception handling in ASP. NET Web API.)

The Web API uses the format specified by the Accept header value in the request message to determine the format of content returned by the response message (that is, the content negotiation method)

For example: Using Chrome's Postman plugin

Specifies that the request header Accept value is: Application/xml returns the XML type data.

Specifies that the request header Accept value is: Application/json returns the JSON type data.

Get start-How to convert a controller's return value to an HTTP response message

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.