【Web API系列教程】1.2 — Web API 2中的Action Results
前言
本节的主题是ASP.NET Web API怎样将控制器动作的返回值转换成HTTP的响应消息。
Web API控制器动作能够返回下列的不论什么值:
1。 void
2。 HttpResponseMessage
3, IHttpActionResult
4, Some other type
取决于返回的以上哪一种。Web API使用不同的机制来创建HTTP响应。
| Return type | How Web API creates the response |
|---|---|
| void | Return empty 204 (No Content) |
| HttpResponseMessage | Convert directly to an HTTP response message. |
| IHttpActionResult | Call ExecuteAsync to create an HttpResponseMessage, then convert to an HTTP response message. |
| Other type | Write the serialized return value into the response body; return 200 (OK). |
本节的剩余部分将具体描写叙述每种返回值。
void
假设返回类型是type,Web API就会用状态码204(No Content)返回一个空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
HttpResponseMessage
假设一个动作返回HttpResponseMessage,Web API就通过HttpResponseMessage的属性构造成消息从而直接将返回值转换成HTTP响应。
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
假设传递一个域模型给CreateResponse方法。Web API会使用媒体格式(media formatter)将序列化模型写入到响应体中。
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;
}
IHttpActionResult
IHttpActionResult接口在Web API 2中被引进。本质上,它定义了一个HttpResponseMessage工厂。下面是使用IHttpActionResult接口的优点:
1, 简单你的控制器的单元測试
2。 为创建HTTP对应将公共逻辑移动到单独的类
3。 通过隐藏构建对应的底层细节。使控制器动作更清晰
IHttpActionResult包括一个单独的方法ExecuteAsync。它会异步地创建一个HttpResponseMessage实例:
public interface IHttpActionResult
{
Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken);
}
假设一个控制器动作返回IHttpActionResult,Web API会调用ExecuteAsync方法来创建HttpResponseMessage。然后将HttpResponseMessage转换到HTTP对应消息里。
下面是一个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);
}
}
控制器动作演示样例:
public class ValuesController : ApiController
{
public IHttpActionResult Get()
{
return new TextResult("hello", Request);
}
}
对应:
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
更通常的情况是,你会使用System.Web.Http.Results命名空间下定义的IHttpActionResult实现。
在接下来的演示样例中,假设请求没有匹配到不论什么已存在的产品ID。控制器就会调用ApiController.NotFound来创建一个404(Not Found)响应。否则,控制器会调用ApiController.OK,它会调用一个意为包括该产品的200(OK)对应。
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 Types
对于其它全部返回类型。Web API使用媒体格式(media formatter)来序列化返回值。
Web API将序列化值写入到响应体中。响应状态码是200(OK)。
public class ProductsController : ApiController
{
public IEnumerable<Product> Get()
{
return GetAllProductsFromDB();
}
}
该实现的缺点在于你不能直接返回一个错误码,比方404。
Web API通过在请求中使用Accept头来选择格式。
演示样例请求:
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系列教程】1.2 — Web API 2中的Action Results的更多相关文章
- ASP.NET Web API系列教程目录
ASP.NET Web API系列教程目录 Introduction:What's This New Web API?引子:新的Web API是什么? Chapter 1: Getting Start ...
- ASP.NET Web API系列教程(目录)(转)
注:微软随ASP.NET MVC 4一起还发布了一个框架,叫做ASP.NET Web API.这是一个用来在.NET平台上建立HTTP服务的Web API框架,是微软的又一项令人振奋的技术.目前,国内 ...
- [转]ASP.NET Web API系列教程(目录)
本文转自:http://www.cnblogs.com/r01cn/archive/2012/11/11/2765432.html 注:微软随ASP.NET MVC 4一起还发布了一个框架,叫做ASP ...
- Web攻防系列教程之文件上传攻防解析(转载)
Web攻防系列教程之文件上传攻防解析: 文件上传是WEB应用很常见的一种功能,本身是一项正常的业务需求,不存在什么问题.但如果在上传时没有对文件进行正确处理,则很可能会发生安全问题.本文将对文件上传的 ...
- Web Api系列教程第2季(OData篇)(二)——使用Web Api创建只读的OData服务
前言 很久没更新了,之前有很多事情,所以拖了很久,非常抱歉.好了,废话不多说,下面开始正题.本篇仍然使用上一季的的项目背景(系列地址http://www.cnblogs.com/fzrain/p/34 ...
- 使用ASP.NET Web Api构建基于REST风格的服务实战系列教程【九】——API变了,客户端怎么办?
系列导航地址http://www.cnblogs.com/fzrain/p/3490137.html 前言 一旦我们将API发布之后,消费者就会开始使用并和其他的一些数据混在一起.然而,当新的需求出现 ...
- 【转】ASP.NET WEB API系列教程
from: 西瓜小强 http://www.cnblogs.com/risk/category/406988.html ASP.NET Web API教程(六) 安全与身份认证 摘要: 在实际的项目应 ...
- [转]Web Api系列教程第2季(OData篇)(二)——使用Web Api创建只读的OData服务
本文转自:http://www.cnblogs.com/fzrain/p/3923727.html 前言 很久没更新了,之前有很多事情,所以拖了很久,非常抱歉.好了,废话不多说,下面开始正题.本篇仍然 ...
- 【Web API系列教程】1.1 — ASP.NET Web API入门
前言 HTTP不仅仅服务于web页面.同一时候也是构建暴露服务和数据的API的强大平台.HTTP有着简单.灵活和无处不在的特点.你能想到的差点儿全部平台都包括有一个HTTP库.所以HTTP服务能够遍及 ...
- 【Web API系列教程】3.3 — 实战:处理数据(建立数据库)
前言 在本部分中,你将在EF上使用Code First Migration来用測试数据建立数据库. 在Tools文件夹下选择Library Package Manager,然后选择Package Ma ...
随机推荐
- 【bzoj1041】[HAOI2008]圆上的整点 数论
题目描述 求一个给定的圆(x^2+y^2=r^2),在圆周上有多少个点的坐标是整数. 输入 只有一个正整数n,n<=2000 000 000 输出 整点个数 样例输入 4 样例输出 4 题解 数 ...
- [AGC004D] Teleporter [贪心]
题面: 传送门 思路: 分析可知,这道题中的图是一个环套内向树,首都在环上 首先有一个结论:当首都的出边指向首都时,一定最优(不然首都出发可能无法按时到达首都)(可以按时到达的情况也一定有到不了的) ...
- docker (centOS 7) 使用笔记5 - weave网络
weave官网 https://www.weave.works 1. 下载安装 sudo curl -L git.io/weave -o /usr/local/bin/weave sudo chmod ...
- 【bzoj3119】Book
小清新题,有手有笔就能做出来了…… 先把 $b$ 取相反数,这样写加法好看. 设 $x,y$,使得 $ax+by=m-np$(其实是懒得想文字定义了),该方程与 $x+y=\frac{n(n-1)}{ ...
- 【小技巧】树剖套线段树优化建图如何做到 O(nlogn)
前提:用树剖套线段树优化树链连边.例题:bzoj4699 我们说树剖的时间复杂度是 $O(n\times log(n))$,是因为访问一条链时需要经过 $log(n)$ 级别条重链,对于每条重链还需要 ...
- shell script 的简单介绍
一 什么叫shell script (程序化脚本)? shell script 是利用 shell 的功能所写的一个 “程序”(program),这个程序是使用纯文本文件,将一些 shell 的语法与 ...
- 《插件》一个比较好用的 chrome浏览器的json格式化插件
插件名: JSON-Handle 下载地址: http://jsonhandle.sinaapp.com/ 插件下载后,在浏览器输入:chrome://extensions/ 将下 ...
- 【05】Vue 之 实例详解与生命周期
Vue的实例是Vue框架的入口,其实也就是前端的ViewModel,它包含了页面中的业务逻辑处理.数据模型等,当然它也有自己的一系列的生命周期的事件钩子,辅助我们进行对整个Vue实例生成.编译.挂着. ...
- JavaScript中in的用法
JavaScript中的in 操作符是对Object(对象)操作的,并不是针对数组. in 的右边必须是对象变量 例如:var data = {id:1, name:'AAA'};if('name' ...
- 【BZOJ4402】Claris的剑(组合计数)
题意: 给定数列的定义: 1.每个元素都是正整数 2.每个元素不能超过M 3.相邻两个元素的差的绝对值必须是1 4.第一个元素的值必须是1 求有多少个长度不超过N的合法的本质不同的序列 两个序列本质不 ...