原文: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. 如何在sqlserver建立新用户并关联相应的数据库

    我们经常需要在数据库上建立有权限的用户,该用户只能去操作某个特定的数据库(比如该用户只能去读,去写等等),那么我们应该怎么在sqlserver上设置呢?下面的步骤有点长,只要一步一步跟着设置就行 方法 ...

  2. SQL从入门到基础 - 07 抑制重复数据

    一.去掉数据重复 distinct 1. Select FDepartment from T_Employee →select distinct FDepartment from T_Employee ...

  3. MongoVUE查询备忘

    用了一段时间的MongoVUE,把一些在MongoVUE中常用的查询记录一下,以便查阅.1.and查询    查询date等于2016-01-08,并且page_url等于shouye.html   ...

  4. C#Graphics画图

    public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { G ...

  5. Cookie 添加,读取,删除

    Name,value – 声明时 new Cookie(key,value); Path        - 默认值,即为当前保存cookie的这个serlvet所在的路径. 如果Cookie在这样的路 ...

  6. 安全性良好的operator=操作,和新的new方法(针对深度复制的情况)

    class B { }; class A { public: A& operator=(const A& a) { B* temp = b; //这里解决重复赋值的方法是用temp指向 ...

  7. c++中static的使用

    static可以用来修饰变量,包括函数的局部变量,类的成员变量.可以用来修饰函数,包括类的成员函数,普通函数. 今天就只说说static修饰类之外的函数的情况.假设你写了一个head.h,一个a.cp ...

  8. c#解析XML和JSON

    http://guwei4037.blog.51cto.com/3052247/1344190  

  9. web前端安全相关

    burpsuite Burp Suite 是用于攻击web 应用程序的集成平台.它包含了许多工具,并为这些工具设计了许多接口,以促进加快攻击应用程序的过程.所有的工具都共享一个能处理并显示HTTP 消 ...

  10. ios如何判断键盘是否已经显示

    ios如何判断键盘是否已经显示   在群里看到有人问:ios如何判断键盘已经显示在界面上. 其实这个解决很简单: 写一个单例来管理键盘的状态. 这个单例在初始化方法init种监听2个事件,分别是 UI ...