WebApi2官网学习记录---批量处理HTTP Message
原文:Batching Handler for ASP.NET Web API
自定义实现
HttpMessageHandlerpublic 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
if ("multipart/batch" !=
request.Content.Headers.ContentType.MediaType)
{
return request.CreateResponse(HttpStatusCode.BadRequest);
} // Start a multipart response
var outerContent = new MultipartContent("batch");
var outerResp = request.CreateResponse();
outerResp.Content = outerContent; // Read the multipart request
var multipart = await request.Content.ReadAsMultipartAsync(); foreach (var httpContent in multipart.Contents)
{
HttpResponseMessage innerResp = null; try
{
// Decode the request object
var innerReq = await
httpContent.ReadAsHttpRequestMessageAsync(); // Send the request through the pipeline
innerResp = await _server.SendAsync(
innerReq,
cancellationToken
);
}
catch (Exception)
{
// If exceptions are thrown, send back generic 400
innerResp = new HttpResponseMessage(
HttpStatusCode.BadRequest
);
} // Wrap the response in a message content and put it
// into the multipart response
outerContent.Add(new HttpMessageContent(innerResp));
} return outerResp;
}
}
配置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 });
模拟请求
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"
)
)
); 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();
}
结果如下:
<<< 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--
<<< RESPONSE >>>
StatusCode: 200,
ReasonPhrase: 'OK',
Version: 1.1,
Content: System.Net.Http.StreamContent,
Headers:
{
Pragma: no-cache
Cache-Control: no-cache
Date: Thu, 21 Jun 2012 00:21:40 GMT
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Content-Length: 658
Content-Type: multipart/batch
Expires: -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
WebApi2官网学习记录---批量处理HTTP Message的更多相关文章
- WebApi2官网学习记录---Cookie
Cookie的几个参数: Domain.Path.Expires.Max-Age 如果Expires与Max-Age都存在,Max-Age优先级高,如果都没有设置cookie会在会话结束后删除cook ...
- WebApi2官网学习记录---Html Form Data
HTML Forms概述 <form action="api/values" method="post"> 默认的method是GET,如果使用GE ...
- WebApi2官网学习记录--HttpClient Message Handlers
在客户端,HttpClient使用message handle处理request.默认的handler是HttpClientHandler,用来发送请求和获取response从服务端.可以在clien ...
- WebApi2官网学习记录--HTTP Message Handlers
Message Handlers是一个接收HTTP Request返回HTTP Response的类,继承自HttpMessageHandler 通常,一些列的message handler被链接到一 ...
- WebApi2官网学习记录---Configuring
Configuration Settings WebAPI中的configuration settings定义在HttpConfiguration中.有一下成员: DependencyResolver ...
- WebApi2官网学习记录--- Authentication与Authorization
Authentication(认证) WebAPI中的认证既可以使用HttpModel也可以使用HTTP message handler,具体使用哪个可以参考一下依据: 一个HttpModel可以 ...
- WebApi2官网学习记录---单元测试
如果没有对应的web api模板,首先使用nuget进行安装 例子1: ProductController 是以硬编码的方式使用StoreAppContext类的实例,可以使用依赖注入模式,在外部指定 ...
- WebApi2官网学习记录---Tracing
安装追踪用的包 Install-Package Microsoft.AspNet.WebApi.Tracing Update-Package Microsoft.AspNet.WebApi.WebHo ...
- WebApi2官网学习记录---异常处理
HttpResponseException 当WebAPI的控制器抛出一个未捕获的异常时,默认情况下,大多数异常被转为status code为500的http response即服务端错误. Http ...
随机推荐
- SQlserver表连接
连接是两元运算,可以对两个或多个表进行查询,结果通常是含有参加连接运算的两个表或多个表的指定列的表. 在T-SQL中,连接查询有两类: 第一类:符合SQL标准的连接谓词表示形式: 第二类:T-SQL扩 ...
- 关于ROW_NUMBER函数的使用(The use of ROW_NUMBER function )
1.用于删除重复记录(The use of to delete the common record) 例子:(Example) #1初始化数据(Initialize the data) CREATE ...
- css3画苹果logo
<!doctype html> <html> <head> <meta charset="utf-8"> <title> ...
- PHP扩展开发(6) - VS2012下strncasecmp和fopen函数warning
1. fopen warning C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s i ...
- DEDE首页调用{dede:field.content/}
过滤DEDE后台自己添加的Class文件和HTML代码: {dede:sql sql='Select content from #@__arctype where id=1'} [field:cont ...
- c语言,全局变量,局部变量,外部函数,内部函数,stasic和extern的复习总结
@import url(http://i.cnblogs.com/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/c ...
- android dom方式创建xml
http://blog.csdn.net/nxh_love/article/details/7085174 在android dom 解析xml方式文章中,简单介绍了dom解析xml的应用.今天在原文 ...
- AD 10 直接出 BOM 的漂亮效果
EDA 工具出BOM 需要什么格式,太多人费尽心思在代码级别做了很多工作,,,,,,,不提,,,,, 真正的BOM 需要东西呢?大家可以讨论讨论.-附件是G41 一个小板的 demo BOM,由AD1 ...
- ISO7816标准IO通讯方面的需求
以下需求适用于符合ISO7816的Reader的测试:换句话说只要Reader能通过以下指令,就基本符合了ISO7816标准,具体需求为: 1 概述 本文档主要描述CDCAS系统中用到的CA证书的格式 ...
- windows driver inf文件
原来修改了inf文件会导致签名过的驱动包哈希值不正确了啊.现在才知道. = = http://www.chiphell.com/thread-827956-1-1.html