web api :Action Results in Web API 2

原文:http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/action-results

Web api 返回以下四种类型:

  1. void

  2. HttpResponseMessage

  3. IHttpActionResult

  4. 其他类型

返回类型 Web API创建的类型
void 204 (No content)
HttpResponseMessage 直接转为一个HTTP响应消息
IHttpActionResult 调用ExecuteAsync创建一个HttpResponseMessage,然后转为一个HTTP响应消息
其他类型 将返回类型序列化,然后返回200(ok)

1.void

如果返回类型是void,Web API简单地反映状态为204(无内容)的空HTTP响应。

代码片段:

public class ValuesController : ApiController 
{ 
    public void Post() 
    {
    } 
}

HTTP响应:

HTTP/1.1 204 No Content 
Server: Microsoft-IIS/8.0 
Date: Mon, 27 Jan 2014 02:13:26 GMT

2.HttpResponseMessage

通过HttpResponseMessage的属性可以添加一些控制。

如:

public class ValuesController : ApiController
{
    public HttpResponseMessage Get()
    {
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value");
        response.Content = new StringContent("hello", Encoding.Unicode);
        response.Headers.CacheControl = new CacheControlHeaderValue()
        {
            MaxAge = TimeSpan.FromMinutes(20)
        };
        return response;
    }
}

响应为:

HTTP/1.1 200 OK 
Cache-Control: max-age=1200 
Content-Length: 10 
Content-Type: text/plain; charset=utf-16 
Server: Microsoft-IIS/8.0 
Date: Mon, 27 Jan 2014 08:53:35 GMT 

hello

3.IHttpActionResult

Web API2才引入IHttpActionResult。

优势:

  • 简化Web API的单元测试

  • 将创建HTTP响应的公共逻辑移到独立的类

  • 通过隐藏构造响应的底层细节,使controller action的意图更加清晰

内置的Result主要是从 System.Web.Http.Results 中寻找,如OkResult。

典型的:

public IHttpActionResult Get (int id)
{
    Product product = _repository.Get (id);
    if (product == null)
    {
        return NotFound(); // Returns a NotFoundResult
    }
    return Ok(product);  // Returns an OkNegotiatedContentResult
}

4.其他类型

Web API 选择正确的formater来序列化对象,并放置在http响应的Body中。

public class ProductsController : ApiController
{
    public IEnumerable<Product> Get()
    {
        return GetAllProductsFromDB();
    }
}

响应:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.0
Date: Mon, 27 Jan 2014 08:53:35 GMT
Content-Length: 56

[{"Id":1,"Name":"Yo-yo","Category":"Toys","Price":6.95}]
posted @ 2016-09-01 22:38  _DN  阅读(169)  评论(0编辑  收藏  举报