原文:Batching Handler for ASP.NET Web API

  1. 自定义实现HttpMessageHandler

       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
    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;
    }
    }
  2. 配置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 });
  3. 模拟请求

     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的更多相关文章

  1. WebApi2官网学习记录---Cookie

    Cookie的几个参数: Domain.Path.Expires.Max-Age 如果Expires与Max-Age都存在,Max-Age优先级高,如果都没有设置cookie会在会话结束后删除cook ...

  2. WebApi2官网学习记录---Html Form Data

    HTML Forms概述 <form action="api/values" method="post"> 默认的method是GET,如果使用GE ...

  3. WebApi2官网学习记录--HttpClient Message Handlers

    在客户端,HttpClient使用message handle处理request.默认的handler是HttpClientHandler,用来发送请求和获取response从服务端.可以在clien ...

  4. WebApi2官网学习记录--HTTP Message Handlers

    Message Handlers是一个接收HTTP Request返回HTTP Response的类,继承自HttpMessageHandler 通常,一些列的message handler被链接到一 ...

  5. WebApi2官网学习记录---Configuring

    Configuration Settings WebAPI中的configuration settings定义在HttpConfiguration中.有一下成员: DependencyResolver ...

  6. WebApi2官网学习记录--- Authentication与Authorization

    Authentication(认证)   WebAPI中的认证既可以使用HttpModel也可以使用HTTP message handler,具体使用哪个可以参考一下依据: 一个HttpModel可以 ...

  7. WebApi2官网学习记录---单元测试

    如果没有对应的web api模板,首先使用nuget进行安装 例子1: ProductController 是以硬编码的方式使用StoreAppContext类的实例,可以使用依赖注入模式,在外部指定 ...

  8. WebApi2官网学习记录---Tracing

    安装追踪用的包 Install-Package Microsoft.AspNet.WebApi.Tracing Update-Package Microsoft.AspNet.WebApi.WebHo ...

  9. WebApi2官网学习记录---异常处理

    HttpResponseException 当WebAPI的控制器抛出一个未捕获的异常时,默认情况下,大多数异常被转为status code为500的http response即服务端错误. Http ...

随机推荐

  1. datagrid的基本操作-增删改

    1 ---恢复内容开始--- <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> ...

  2. (转)函数中使用 ajax 异步 同步 返回值错误 主函数显示返回值总是undefined -- ajax使用总结

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAloAAAE0CAIAAAB7LwoKAAAgAElEQVR4nO2dy6sc152A6+/R2mXwSn ...

  3. c# 基础复习1

    1. 类和对象 1.1 类和对象的概念 类:对象的类型,它不同于 int 等基本数据类型,因为类具有行为:也可以说是具有相 同特征和行为的一组对象的集合. 对象:对象是一个个你能看得见,摸得着的实体, ...

  4. 网狐6603 cocos2dx 棋牌、捕鱼、休闲类游戏《李逵捕鱼》手机端完整源码分析及分享

    该资源说明: cocos2d 棋牌.捕鱼.休闲类游戏<李逵捕鱼>手机端完整源码,网狐6603配套手机版源码,可以选桌子,适合新手学习参考,小编已亲测试,绝对完整可编译手机端,下载后将文件考 ...

  5. iOS学习之页面之间传值的方式总结

    传值三种场景: 1.属性传值(从前往后传) 需求:第二个界面标签显示第一个界面输入框文字. 第一步, 在前一个界面定义属性. (语义属性声明为copy); 第二步, 在进入下一个界面之前,给属性传入数 ...

  6. C 语言简历一个文件夹 并自己输入字符 来取文件夹名字

    int main(void) { FILE *fp; char ch,filename[10]; scanf("%s",filename); if((fp=fopen(filena ...

  7. hdu 2019

    Problem Description 有n(n<=100)个整数,已经按照从小到大顺序排列好,现在另外给一个整数x,请将该数插入到序列中,并使新的序列仍然有序.   Input 输入数据包含多 ...

  8. 更新项目经常使用的Linux命令

    在公司经常在服务器上更新项目,总结了自己经常使用的命令: 1.删除:rm -rf 文件名2.复制:copy 文件 目标地址3.压缩:zip -r 压缩后文件名 被压缩目录4.移动:move 文件 目标 ...

  9. Proguard中optimize设置不当引发SimException

    今天来说一下Proguard中关于optimize的问题.先上一张异常图片 最近项目重构,重新调整了各个组件之间的依赖关系.过程中,在项目Proguard这块卡住了,最开始还好,Proguard只是提 ...

  10. commons-pool2-中的一些配置

      /**                     * 连接失效检测相关                     */                    // 空闲时进行连接测试,会启动异步evi ...