Asp.Net WebAPI服務函數的返回值主要可以分為void、普通對象、HttpResponseMessag、IHttpActionResult e四種,本文這里簡單的介紹一下它們的區別。
一、返回void
返回void一般常用於Put和Delete函數。
public void Delete(int id)
{
}
當服務函數執行完成后,服務器端並不是啥都不干直接把客戶端給斷掉,而是發送一個標准的204 (No Content)的Http應答給客戶端。
HTTP/1.1 204 No Content
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?Zjpc5paH5qGjXHZpc3VhbCBzdHVkaW8gMjAxM1xQcm9qZWN0c1xXZWJBcHBsaWNhdGlvbjFcV2ViQXBwbGljYXRpb24xXGFwaVx2YWx1ZXNcMQ==?=
X-Powered-By: ASP.NET
Date: Fri, 02 May 2014 13:32:07 GMT
二、返回普通對象
返回普通對象時,服務器將返回的對象序列化后(默認是json),通過Http應答返回給客戶端。例如,
public class ValuesController : ApiController
{
public string Get()
{
return "hello";
}
}
此時的返回結果是:
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?Zjpc5paH5qGjXHZpc3VhbCBzdHVkaW8gMjAxM1xQcm9qZWN0c1xXZWJBcHBsaWNhdGlvbjFcV2ViQXBwbGljYXRpb24xXGFwaVx2YWx1ZXM=?=
X-Powered-By: ASP.NET
Date: Fri, 02 May 2014 12:54:18 GMT
Content-Length: 7
"hello"
異步返回普通對象:
WebAPI也是支持異步返回對象的:
public async Task<string> Get()
{
await Task.Delay(100);
return "hello";
}
異步返回的時候,服務器異步等待函數執行完成后再將返回值返回給對象。由於這個過程對於客戶端來說是透明的,這里就不列舉報文了。
三、返回HttpResponseMessage
HttpResponseMessage是標准Http應答了,此時服務器並不做任何處理,直接將HttpResponseMessage發送給客戶端。
public HttpResponseMessage Get()
{
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent("hello", Encoding.UTF8);
return response;
}
此時的返回結果如下:
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Length: 5
Content-Type: text/plain; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?Zjpc5paH5qGjXHZpc3VhbCBzdHVkaW8gMjAxM1xQcm9qZWN0c1xXZWJBcHBsaWNhdGlvbjFcV2ViQXBwbGljYXRpb24xXGFwaVx2YWx1ZXM=?=
X-Powered-By: ASP.NET
Date: Fri, 02 May 2014 13:09:57 GMT
hello
可以看到,這里返回的content-type仍然是原始定義的text類型,而不是json。要實現想上面的例子所示的結果,則需要將Get函數改寫為如下形式
public HttpResponseMessage Get()
{
return Request.CreateResponse(HttpStatusCode.OK, "hello");
}
四、返回IHttpActionResult
IHttpActionResult是Web API 2中引入的一個接口,它的定義如下:
public interface IHttpActionResult
{
Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken);
}
從它的定義可以看出,IHttpActionResult是HttpResponseMessage的一個工廠類,最終還是用於構建HttpResponseMessage返回,由於它可以取消,因而可以實現更為強大的返回功能(如流傳輸)。當服務函數返回IHttpActionResult對象時,服務器執行該對象的ExecuteAsync函數,並異步等待至函數完成后,獲取其返回值HttpResponseMessage輸出給客戶端。
IHttpActionResult是WebAPI中推薦的標准返回值,ApiController類中也提供了不少標准的工廠函數方便我們快速構建它們,如BadRequest,Conflict,Ok,NotFound等,一個簡單的示例如下:
public IHttpActionResult Get(int id)
{
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
參考文章: http://www.asp.net/web-api/overview/web-api-routing-and-actions/action-results