Web API 2中的Action Results
[译]Action Results in Web API 2
单击此处查看原文
本文阐述了ASP.NET Web API是如何将controller action的返回值转换为HTTP response message的。
一个Web API controller action可以有以下几种返回值:
- void
- HttpResponseMessage
- IHttpActionResult
- Some other type(其他)
根据以上四种返回类型的不同,Web API会使用不同的机制创建HTTP response。
| 返回类型 | 创建方式 |
|---|---|
| void | 无内容 |
| HttpResponseMessage | 直接转换为Http response message |
| IHttpActionResult | 调用ExecuteAsync来创建一个HttpResponseMessage,然后转换为Http response message |
| Other Type | 将序列化的返回值写入response body;返回 状态码200(OK) |
本文的其余部分将阐述以上四种情况的详细内容。
void
如果返回类型是void,Web API会直接返回一个空的HTTP response,状态码:200,表示无内容。
示例controller:
public class ValuesController : ApiController
{
public void Post()
{
}
}
HTTP response:
HTTP/1.1 204 No Content
Server: Microsoft-IIS/8.0
Date: Mon, 27 Jan 2014 02:13:26 GMT
HttpResponseMessage
如果action返回了一个HttpResponseMessage,Web API会将该返回值转换为一个HTTP response message,使用HttpResponseMessage对象的属性来填充这个HTTP response message。
下面的示例代码中对一个response message 进行了大量的控制。比如:它设置了Cache-Control header。
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
如果你通过使用一个domain model(领域模型)来使用CreateResponse方法,Web API使用media formatter来将序列化的模型写入response body。
public HttpResponseMessage Get()
{
// Get a list of products from a database.
IEnumerable<Product> products = GetProductsFromDB();
// Write the list to the response body.
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, products);
return response;
}
Web API在请求中使用Accept header来选择formatter。更多详情,参见Content Negotiation。
IHttpActionResult
IHttpActionResult接口在Web API 2中有过相关介绍。它主要定义了一个**HttpResponseMessage **factory。使用此接口有以下的几点优势:
- 简化了你对controllers进行的unit test
- 将创建Http responses的通用逻辑分离到独立的类中
- 通过隐藏构建response的底层实现细节,使得controller action的功能简介明了
IHttpActionResult声明了一个方法:ExecuteAsync,用于异步创建HttpResponseMessage实例。
public interface IHttpActionResult
{
Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken);
}
如果一个controller action返回一个IHttpActionResult,Web API 将调用ExecuteAsync方法来创建一个HttpResponseMessage。然后它再将HttpResponseMessage转换为一个HTTP response message。
以下是一个IHttpActionResult接口的简单实现,它会创建一个纯文本的响应。
public class TextResult : IHttpActionResult
{
string _value;
HttpRequestMessage _request;
public TextResult(string value, HttpRequestMessage request)
{
_value = value;
_request = request;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = new HttpResponseMessage()
{
Content = new StringContent(_value),
RequestMessage = _request
};
return Task.FromResult(response);
}
}
controller action:
public class ValuesController : ApiController
{
public IHttpActionResult Get()
{
return new TextResult("hello", Request);
}
}
response:
HTTP/1.1 200 OK
Content-Length: 5
Content-Type: text/plain; charset=utf-8
Server: Microsoft-IIS/8.0
Date: Mon, 27 Jan 2014 08:53:35 GMT
hello
通常你需要将IHttpActionResult的实现写在System.Web.Http.Results命名空间下。因为ApiController定义的helper method会返回这些内置的action results。
下面的示例中,如果一个请求没有匹配到现有的product ID,这个controller将调用ApiController.NotFound来创建一个404(Not Found) response。否则,controller将调用ApiController.OK,来创建一个200(OK) response,它包含了product信息。
public IHttpActionResult Get (int id)
{
Product product = _repository.Get (id);
if (product == null)
{
return NotFound(); // Returns a NotFoundResult
}
return Ok(product); // Returns an OkNegotiatedContentResult
}
Other Return Type
如果返回类型是其他任何的一种形式,Web API使用了一个media formatter来序列化这些返回值,然后将这些序列化的值写入response body。这个response status code是200(ok)。
public class ProductsController : ApiController
{
public IEnumerable<Product> Get()
{
return GetAllProductsFromDB();
}
}
使用这种方法的缺点是,你无法直接返回一个error code,比如404。不过你可以抛出一个HttpResponseException异常来替代error code。更多详情,参见Exception Handling in ASP.NET Web API。
Web API在请求中使用Accept header来选择formatter。更多详情,参见Content Negotiation。
示例请求:
GET http://localhost/api/products HTTP/1.1
User-Agent: Fiddler
Host: localhost:24127
Accept: application/json
示例响应:
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}]
Web API 2中的Action Results的更多相关文章
- 【Web API系列教程】1.2 — Web API 2中的Action Results
前言 本节的主题是ASP.NET Web API怎样将控制器动作的返回值转换成HTTP的响应消息. Web API控制器动作能够返回下列的不论什么值: 1. void 2. HttpResponseM ...
- Web API项目中使用Area对业务进行分类管理
在之前开发的很多Web API项目中,为了方便以及快速开发,往往把整个Web API的控制器放在基目录的Controllers目录中,但随着业务越来越复杂,这样Controllers目录中的文件就增加 ...
- Web API 2中的属性路由
Web API 2中的属性路由 前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.ht ...
- 从ASP.Net Core Web Api模板中移除MVC Razor依赖项
前言 :本篇文章,我将会介绍如何在不包括MVC / Razor功能和包的情况下,添加最少的依赖项到ASP.NET Core Web API项目中. 一.MVC VS WebApi (1)在ASP. ...
- [译] 在Web API 2 中实现带JSON的Patch请求
原文链接:The Patch Verb in Web API 2 with JSON 我想在.NET4.6 Web API 2 项目中使用Patch更新一个大对象中的某个字断,这才意识到我以前都没有用 ...
- ASP.NET Web API 2 中的属性路由使用(转载)
转载地址:ASP.NET Web API 2 中的属性路由使用
- ASP.NET Web API 2中的错误处理
前几天在webapi项目中遇到一个问题:Controller构造函数中抛出异常时全局过滤器捕获不到,于是网搜一把写下这篇博客作为总结. HttpResponseException 通常在WebAPI的 ...
- Web API 2中的操作结果
how ASP.NET Web API converts the return value from a controller action into an HTTP response message ...
- Web APi之控制器选择Action方法过程(九)
前言 前面我们叙述了关于控制器创建的详细过程,在前面完成了对控制器的激活之后,就是根据控制器信息来查找匹配的Action方法,这就是本节要讲的内容.当请求过来时首先经过宿主处理管道然后进入Web AP ...
随机推荐
- Java程序单元测试工具对比——Parasoft Jtest与Junit
Web应用程序开发中,面向对象的Java语言占了不少的比重.对于Java应用程序的测试方法或方式多种多样,比较典型的是程序员自己来完成程序测试中的一个部分——单元测试. 之前,慧都资讯提到单元测试是程 ...
- UC编程:环境变量的查询与修改
每个程序中都维护一个指向环境变量的指针char **environ; 子进程会从父进程继承环境变量.子进程环境变量的修改不一定会影响父进程 无关的多个进程之间修改环境变量不会互相影响 打印环境变量 [ ...
- C#泛型回顾点滴
前言 C#的泛型一直是学习者津津乐道的课题了,这确实是一个非常有用的特性,不过在实际使用中,还是有很多需要注意的地方,我们需要通过自己动手实践以及结合理论进行理解,最终总结出自己的编码规范和最佳实践 ...
- jsp连接MySQL数据库显示GIS地理数据乱码问题的解决(select AsText(the_geom))
oh,fuck,经过我昨天下午到今天的努力,终于将这一问题成功解决了,哈哈哈 问题详细描述: 我通过jsp页面连接上MySQL数据库,取出存在表中的地理数据(类型是geometry,具体有POINT. ...
- 修改servu数据库密码 servu加密方式
项目要求可以有用户自行修改servu密码.servu可以通过odbc访问access\mysql\sqlserver数据库.我们直接通过创建web来修改就可以了. 不过问题来了,密码是加密的...通过 ...
- WCF 采用net.tcp协议
WCF 采用net.tcp协议实践 概述 与Socket相比,WCF真是爽得不得了,其基本指导思想为SOA——面向服务. 其基本配置在于ABC(Address,Binding,Contract), ...
- 使用maven+eclipse搭建最简单的struts2的helloworld
使用maven+eclipse搭建最简单的struts2的helloworld 一.web分层结构简介 1.web[细]粒度分层结构: 按细粒度分层可以分为以下6种: 1).表现层:html/css/ ...
- ASP.NET服务器端事件利用MARQUEE实现正在处理效果
前言:ASP.NET同仁们应该都遇到过当触发一个比较耗时的服务器端事件时,页面会处在一个等待的状态(即假死状态),用户体验非常不好,很容易造成用户二次点击,造成重复提交.至于解决方案自然是有的(问go ...
- js闭包(转)
一.变量的作用域 要理解闭包,首先必须理解Javascript特殊的变量作用域. 变量的作用域无非就是两种:全局变量和局部变量. Javascript语言的特殊之处,就在于函数内部可以直接读取全局变量 ...
- Sublime2 Text编辑器使用技巧
Sublime2 Text编辑器使用技巧 ------------------------------------软件使用----------------------------------- ...