使用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

相关文章
相关标签/搜索