This article is mainly translated from English, the original address http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/action-results
This article focuses on how ASP. NET Webapi translates API return values to HTTP response messages.
A WEBAPI can return one of the following types:
1. void
2,httpresponsemessage
3,Ihttpactionresult
4. Other types
More of the different return types above, WEBAPI uses different mechanisms to create HTTP response messages.
Return Type | How
Web 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 first side introduces four types of details.
void
If the API function return type is VOID,WEBAPI, a null HTTP response message with a status code of 204 will be returned, as in the following code:
Public class valuescontroller:apicontroller{ publicvoid Post () { }}
HTTP Response:
http/1.1204 No contentserver:microsoft-iis/8.0 the from:+ GMT
Httpresponsemessage
If the Httpresponsemessage type is returned, the Web API converts the return value directly into an HTTP response message and populates the response with the Httpresponsemessage Property object. As follows:
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; }}
HTTP response:
http/1.1 OKCache-control:max-age=1200Content10 Content-type:text/plain; charset=utf-server:microsoft-iis/8.0 : £º Gmthello
The above code creates a Httpresponsemessage type variable, directly using the value originally returned to generate the Httpresponsemessage variable. The variable is then returned.
Ihttpactionresult
The Ihttpactionresult interface is defined in Webapi 2. It defines a httpresponsemessage factory. It defines a simple function Executeasync, which is used to asynchronously Httpresponsemessage
Public Interface ihttpactionresult{ Task<HttpResponseMessage>
If the API returns IHTTPACTIONRESULT,WEBAPI call the executeasync function to create a httpresponsemessage. The httpresponsemessage is then converted to an HTTP response message.
Public class valuescontroller : apicontroller{ public ihttpactionresult< Span class= "PLN" > get () { return newtextresult ( "hello" , Span class= "Typ" >request); }} /span>
HTTP response:
http/1.1 okcontent5Content-type:text/plain; charset=utf-8server:microsoft-iis/8.008 :+: Gmthello
Other types
......
WEBAPI Learning Notes API and return type (Action Results in Web API 2)