使用ASP.Net WebAPI構建REST服務(三)——返回值

Asp.Net WebAPI服務函數的返回值主要能夠分爲void、普通對象、HttpResponseMessag、IHttpActionResult e四種,本文這裏簡單的介紹一下它們的區別。web

1、返回void json

返回void通常經常使用於Put和Delete函數。api

    public void Delete(int id)
    {
    }
服務器

當服務函數執行完成後,服務器端並非啥都不幹直接把客戶端給斷掉,而是發送一個標準的204 (No Content)的Http應答給客戶端。 app

    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
asp.net

 

2、返回普通對象 異步

返回普通對象時,服務器將返回的對象序列化後(默認是json),經過Http應答返回給客戶端。例如, async

    public class ValuesController : ApiController
    {
        public string Get()
        {
            return "hello";
        }
    }
函數

此時的返回結果是: spa

    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";
    }

異步返回的時候,服務器異步等待函數執行完成後再將返回值返回給對象。因爲這個過程對於客戶端來講是透明的,這裏就不列舉報文了。

 

3、返回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");
    }

 

4、返回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

相關文章
相關標籤/搜索