【ASP.NET Web API教程】5.4 ASP.NET Web API批处理器

【ASP.NET Web API教程】5.4 ASP.NET Web API批处理器
原文:【ASP.NET Web API教程】5.4 ASP.NET Web API批处理器

注:本文是【ASP.NET Web API系列教程】的一部分,如果您是第一次看本系列教程,请先看前面的内容。

Batching Handler for ASP.NET Web API
5.4 ASP.NET Web API批处理器

本文引自:http://bradwilson.typepad.com/blog/2012/06/batching-handler-for-web-api.html

Brad Wilson | June 20, 2012
作者:Brad Wilson | 日期:2012-6-20

While there is no batching standard built into the HTTP protocol, there is a standard for MIME encoding HTTP request and response messages ("application/http" with "msgtype=request" and "msgtype=response", respectively). ASP.NET Web API has built-in support for both MIME multipart as well as encoded request and response messages, so we have all the building blocks we need to make a simple batch request handler.
当批处理标准尚未进入HTTP协议时,就已经有了对HTTP请求和响应消息进行编码的MIME标准(分别采用“msgtype=request”和“msgtype=response”的“application/http”)。ASP.NET Web API对MIME的multipart(多部分内容类型)、以及经过编码请求和响应消息都有内建的支持,因此,我们拥有了制作简单的请求批处理器的全部构建块。

All we need to make this work is an endpoint which can accept a multipart batch (an invention of our own), which then parses the requests, runs them sequentially, and returns the responses back in a multipart batch response.
我们所要做的全部工作只是一个端点(endpoint),它可以接收一个multipart batch(多部批,一个我们自己发明的内容类型),然后用它对请求进行解析,按顺序执行请求,并以一个multipart batch响应的形式返回一个响应。

Starting with a Web API project (built against the latest nightly build), I updated the Web API config to look like this:
从一个Web API项目(根据最新版建立的项目)开始,我修改了Web API的config,它看上去像这样:

var batchHandler = new BatchHandler(config);
config.Routes.MapHttpRoute("batch", "api/batch",null, null, batchHandler);
config.Routes.MapHttpRoute("default", "api/{controller}/{id}",new { id = RouteParameter.Optional });

I've inserted the handler for "api/batch" as our endpoint for batching requests, using the new "route-specific endpoint handler" feature in Web API. Note that since its URL is "api/batch", I made sure to add it before the default API route.
我已经为“api/batch”插入了处理器,以此作为对请求进行批处理的端点,这种做法利用了Web API中的“路由专用的端点处理器”特性。注,由于它的URL是“api/batch”,必须把它添加在默认的API路由之前

Using async & await in .NET 4.5 makes the implementation of BatchHandler fairly straight-forward. All we need is an in-memory HttpServer which uses our existing configuration, so that the batched requests hit the exact same endpoints as requests from the Internet:
利用.NET 4.5中的async和await可以很直接地构造BatchHandler实现。我们所需要的只是一个放在内存中的HttpServer,它使用当前配置,以便当请求来自Internet时,需要分批的请求会找到完全相同的端点:

public class BatchHandler : HttpMessageHandler
{HttpMessageInvoker _server; 
public BatchHandler(HttpConfiguration config){_server = new HttpMessageInvoker(new HttpServer(config));}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken cancellationToken){// Return 400 for the wrong MIME type// 对于错误的MIME类型,返回400if ("multipart/batch" !=request.Content.Headers.ContentType.MediaType){return request.CreateResponse(HttpStatusCode.BadRequest);}
// Start a multipart response // 启动一个multipart响应var outerContent = new MultipartContent("batch");var outerResp = request.CreateResponse();outerResp.Content = outerContent;
// Read the multipart request// 读取multipart请求var multipart = await request.Content.ReadAsMultipartAsync();foreach (var httpContent in multipart.Contents){HttpResponseMessage innerResp = null;try{// Decode the request object// 解码请求对象var innerReq = awaithttpContent.ReadAsHttpRequestMessageAsync();
// Send the request through the pipeline// 通过管线发送请求innerResp = await _server.SendAsync(innerReq,cancellationToken);}catch (Exception){// If exceptions are thrown, send back generic 400// 如果抛出异常,回发泛型的400innerResp = new HttpResponseMessage(HttpStatusCode.BadRequest);}
// Wrap the response in a message content and put it// into the multipart response// 在消息内容中封装响应,并把它放入multipart响应outerContent.Add(new HttpMessageContent(innerResp));}
return outerResp;} }

Now we have an endpoint that we can send multipart/batch requests to, which are assumed to be HTTP request objects (anything which isn't is going to yield a 400).
现在,我们拥有了一个端点,我们能够把multipart/batch请求发送给它,假设这些请求都是HTTP请求对象(任何不是HTTP请求的对象都会产生一个400状态码)。

On the client side, we make a multipart request and push requests into the multipart batch, one at a time:
在客户端,我们形成了一个multipart请求,并把请求推入multipart batch,每次压入一个请求:

var client = new HttpClient();
var batchRequest = new HttpRequestMessage(HttpMethod.Post,"http://localhost/api/batch"
); 
var batchContent = new MultipartContent("batch"); batchRequest.Content = batchContent;
batchContent.Add(new HttpMessageContent(new HttpRequestMessage(HttpMethod.Get,"http://localhost/api/values")) );
batchContent.Add(new HttpMessageContent(new HttpRequestMessage(HttpMethod.Get,"http://localhost/foo/bar")) );
batchContent.Add(new HttpMessageContent(new HttpRequestMessage(HttpMethod.Get,"http://localhost/api/values/1")) );

In a console application, we can log both the request and response with code like this:
在一个控制台应用程序中,我们可以用以下代码对请求和响应时行日志:

using (Stream stdout = Console.OpenStandardOutput())
{Console.WriteLine("<<< REQUEST >>>");Console.WriteLine();Console.WriteLine(batchRequest);Console.WriteLine();
batchContent.CopyToAsync(stdout).Wait();
Console.WriteLine();var batchResponse = client.SendAsync(batchRequest).Result;Console.WriteLine("<<< RESPONSE >>>");Console.WriteLine();Console.WriteLine(batchResponse);Console.WriteLine();batchResponse.Content.CopyToAsync(stdout).Wait();Console.WriteLine();Console.WriteLine(); }

When I run this console application, I see output similar to this:
当运行这个控制台应用程序时,会看到输出类似于这样:

<<< REQUEST >>> 
Method: POST, RequestUri: 'http://localhost/api/batch', Version: 1.1, Content: System.Net.Http.MultipartContent, Headers: {Content-Type: multipart/batch; boundary="3bc5bd67-3517-4cd0-bcdd-9d23f3850402" }
--3bc5bd67-3517-4cd0-bcdd-9d23f3850402 Content-Type: application/http; msgtype=request
GET /api/values HTTP/1.1 Host: localhost
--3bc5bd67-3517-4cd0-bcdd-9d23f3850402 Content-Type: application/http; msgtype=request GET /foo/bar HTTP/1.1 Host: localhost
--3bc5bd67-3517-4cd0-bcdd-9d23f3850402 Content-Type: application/http; msgtype=request
GET /api/values/1 HTTP/1.1 Host: localhost
--3bc5bd67-3517-4cd0-bcdd-9d23f3850402-- <<< RESPONSE >>>
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: {Pragma: no-cacheCache-Control: no-cacheDate: Thu, 21 Jun 2012 00:21:40 GMTServer: Microsoft-IIS/8.0X-AspNet-Version: 4.0.30319X-Powered-By: ASP.NETContent-Length: 658Content-Type: multipart/batchExpires: -1 }
--3d1ba137-ea6a-40d9-8e34-1b8812394baa Content-Type: application/http; msgtype=response
HTTP/1.1 200 OK Content-Type: application/json; charset=utf-8
["Hello","world!"]
--3d1ba137-ea6a-40d9-8e34-1b8812394baa Content-Type: application/http; msgtype=response
HTTP/1.1 404 Not Found Content-Type: application/json; charset=utf-8
{"Message":"No HTTP resource was found that matches the request URI 'http://localhost/foo/bar'."}
--3d1ba137-ea6a-40d9-8e34-1b8812394baa Content-Type: application/http; msgtype=response
HTTP/1.1 200 OK Content-Type: application/json; charset=utf-8
"world!" --3d1ba137-ea6a-40d9-8e34-1b8812394baa--

As you can see, our batch was successfully run, and the results show what we'd expected (the two real API calls returned back 200 with their data, and the bogus request we threw in the middle returns back a 404).
正如我们所看到的,批处理成功地运行了,并且显示了我们所期望的结果(两个真正的API调用返回了带有其数据的200状态码,而在中间压入的伪造请求返回了404状态码)。


看完此文如果觉得有所收获,请给个推荐

posted on 2014-02-22 15:20 NET未来之路 阅读(...) 评论(...) 编辑 收藏

转载于:https://www.cnblogs.com/lonelyxmas/p/3560881.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/360103.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

linux 查看系统组账号密码是什么,Linux 用户与组管理详解(system-config-users 命令行)...

用户与组管理用户相关文件组账号相关文件用户和组管理软件&#xff1a;基于命令行的用户和组管理创建用户查看用户信息删除用户修改用户信息为用户创建密码更改用户密码信息创建组删除组查看当前登录到系统的用户用户与组管理什么是用户&#xff0c;用户是人吗&#xff1f;用户…

C++中指针和引用的选择

何时使用引用和指针1. 尽可能使用引用传递参数2. 尽可能的使用const来保护引用和指针3. 在可以使用引用的时候不要使用指针4. 不要试图给引用重新赋值&#xff0c;使之指向另一个变量&#xff0c;这是不可能的&#xff08;因为引用是变量的别名&#xff0c;和变量是统一的&…

linux 7 没有权限访问,[CentOS 7系列]文件或目录的权限与属性

在开始今天的话题之前&#xff0c;我们首先来回顾下ls命令。在ls命令中参数“-l”会显示出来目标的详细信息&#xff0c;如下所示&#xff1a;[rootserver02~]#ls-l/tmp/总用量4-rwx------.1rootroot8365月2706:19ks-script-ogzDFAdrwxr-xr-x.5rootroot755月3005:26testdrwxr-x…

POJ 2386 Lake Counting DFS水水

http://poj.org/problem?id2386 题目大意&#xff1a; 有一个大小为N*M的园子&#xff0c;雨后积起了水。八连通的积水被认为是连接在一起的。请求出院子里共有多少水洼&#xff1f; 思路&#xff1a; 水题~直接DFS&#xff0c;DFS过程把途中表示水洼的W改为‘.&#xff0c;看…

linux没有root密码xshell,LINUX终端免密登陆(以Xshell为例)

1&#xff0c;工具-新建用户密钥生成向导linux2&#xff0c;密钥类型选择&#xff1a;RSA&#xff0c;而后下一步shell3&#xff0c;输入密钥名称和密码ssh4&#xff0c;公钥格式为SSH-OpenSSH,保存为文件(后缀为pub)(记录此文件目录)工具二&#xff0c;登陆在须要免密登陆的主…

ActionBar之style出现Cannot resolve symbol 'Theme' 错误

今天 2014/03/08 00:49 刚刚升级 android studio 到了 0.5.0 版本&#xff0c;修复了许多 bug&#xff0c;包含当前这个问题&#xff0c;之前一直困扰我很久&#xff0c;莫名奇妙的提示主题样式找不到&#xff0c;无法解析&#xff0c; 后来一直谷歌发现很多人都认为是 IDE 的b…

单片机上运行linux程序代码,在Linux下烧录51单片机

原标题&#xff1a;在Linux下烧录51单片机*本文作者&#xff1a;LEdge1&#xff0c;本文属 FreeBuf原创奖励计划&#xff0c;未经许可禁止转载。背景我一直在学习Linux 系统&#xff0c;但是最近还要学习51单片机&#xff0c;所以在Linux下给51单片机烧录程序那是非常必要的。之…

linux运行core控制台程序,VisualStudioCode创建的asp.net core控制台程序部署到linux

1、asp.net core控制台程序static void Main(string[] args){int times10;while(times>0){Console.WriteLine("Hello World!");times--;Thread.Sleep(1000);}}2、发布发布前&#xff0c;修改test2.csproj文件(项目名称为test2)Exenetcoreapp2.1centos.7-x64主要添…

StringTokenizer(字符串分隔解析类型)

java.util.StringTokenizer 功效:将字符串以定界符为界&#xff0c;分析为一个个的token&#xff08;可理解为单词&#xff09;&#xff0c;定界符可以自己指定。 &#xff11;、构造函数。1. StringTokenizer(String str) &#xff1a;构造一个用来解析str的StringTokenizer对…

linux 秒数转时间格式,通过delphi将秒数转换成日期格式

摘要将秒数转换成日期格式&#xff0c;是经常用到的一个算法&#xff0c;下面有几个方法&#xff0c;可以借鉴具体代码1&#xff1a;转换成HH:MM:SS格式的字符串格式&#xff1a;function SecondToTime(a:integer):string;beginresult:timetostr(a/86400);end;或者function Sec…

Watch online

1.youku 在优酷看视视频时可登录m.youku.com/wap,在IE上都不需wap,但在chrome上不加会自动跳转成www.youku.com。那上面的视频是一个整体&#xff0c;可以用迅雷下也可在浏览器上直接看。 随便搜了下&#xff0c;发现可直接利用www.youku.com上的视频ID找到上述可直接播放下载的…

java开机自启动 Linux,java项目jar包开机自启(WINDOWS,Linux)

WINDOWS:1.新建一个text文件&#xff0c;将 java -jar D:\eclipse-workspace\attendance\target\mybatis-generator.jar写入&#xff0c;修改文件为.bat文件。2.编写run.vbs文件&#xff0c;新建一个run.text文件&#xff0c;将下面代码写入,然后将文件后缀改为.vbsSet ws Cre…

PHP中,json汉字编码

当用json与js或者其它客户端交互时&#xff0c;如果有中文&#xff0c;则会变成unicode。虽然能使用&#xff0c;但是影响观看。不好调试呀。从网上找到了几个方法 一&#xff0c;用下面这个函数&#xff0c;需要编码时&#xff0c;直接调用这个函数就成 function jsonEnco…

[收藏] Opera鼠标手势命令

Opera的Presto内核版本已经不复存在了&#xff01;&#xff01;惋惜&#xff01;痛惜&#xff01; 现在我的电脑硬盘里还保存着两个版本&#xff0c;一个是第三方优化版的v11.00 1156&#xff0c;另一个是Presto的最终官方版&#xff1a;v12.16&#xff0c;现在看起来都有一种莫…

收到有关RabbitMQ集群分区的通知

如果您在集群中运行RabbitMQ&#xff0c;则集群不太可能会被分区 &#xff08;集群的一部分失去与其余部分的连接&#xff09;。 上面的链接页面介绍了显示状态和配置行为的基本命令。 当发生分区时&#xff0c;您首先希望得到通知&#xff0c;然后进行解决。 RabbitMQ实际上使…

wps linux版本支持vba,Wps vba安装包

wps vba是款专用于wps办公软件的宏插件&#xff0c;可以利用VBA制作Excel登录系统&#xff0c;实现一些VB无法实现的功能&#xff0c;操作界面人性化&#xff0c;方便用户的操作&#xff0c;还可以利用VBA来Excel内轻松开发出功能强大的自动化程序。软件简介&#xff1a;wps vb…

九度 1474:矩阵幂(二分法)

题目描述&#xff1a; 给定一个n*n的矩阵&#xff0c;求该矩阵的k次幂&#xff0c;即P^k 思路 1. 和求解整数幂的思路相同, 使用分治策略, 代码的框架是 int pow(a, b) { c pow(a, b/2) c* c; if(b 为奇数) c * a; return c } 2. 这道题求的是矩阵, 上面的框架不太好用, 毕竟返…

我的Dojo中有一个Mojo(如何编写Maven插件)

我一直忙于在工作中使用Maven的腋窝。 对于很多开发人员&#xff0c;我会听到&#xff1a;“那又怎样。” 不同之处在于&#xff0c;我通常在无法直接访问Internet的环境中工作。 因此&#xff0c;当我说我经常使用Maven时&#xff0c;这意味着某些事情。 依赖地狱 公平地说&a…

linux安装程序过程,linux 应用程序安装过程

四.GRUB安装方式:(1)tar zxvf grub-0.5.96.1.tar.gz(2)cd grub-0.5.96.1(3)./configure(4)make(5)make check(6)make install(7)cp r /usr/local/share/grub/i386-pc/ /boot/grub/(8)vi /boot/menu.lst (内容参考grub-0.5.96.1/docs/menu.lst)例参考如:## /boot/grub/menu.lst …

在linux下安装mongo数据库,Linux系统下安装MongoDB

MongoDB提供了Linux系统上32位和64位的安装包&#xff0c;你可以在官网下载安装包。下载完安装包&#xff0c;并解压 tgz(以下演示的是 64 位 Linux上的安装) 。curl-O https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.0.6.tgz # 下载tar-zxvf mongodb-linux-x86_64-…