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

时间:2023-03-09 00:00:43
使用ASP.Net WebAPI构建REST服务(三)——返回值

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