【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.
原文: 【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类型,返回400 if ("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 = 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 // 如果抛出异常,回发泛型的400 innerResp = 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-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
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状态码)。


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

目录
相关文章
|
13天前
|
开发框架 监控 .NET
Visual Basic的Web服务和REST API开发指南
【4月更文挑战第27天】本文探讨了使用Visual Basic(VB.NET)构建Web服务和RESTful API的方法。首先介绍了Web服务的基础和REST API的概念,然后阐述了.NET Framework与.NET Core/.NET 5+对VB.NET的支持,以及ASP.NET Core在Web开发中的作用。接着,详细讲解了创建RESTful API的步骤,包括控制器与路由设置、模型绑定与验证,以及返回响应。此外,还讨论了安全措施、测试方法、部署选项和监控策略。最后强调,VB.NET开发者可以通过ASP.NET Core涉足现代Web服务开发,拓宽技术领域。
|
10天前
|
弹性计算 JSON Shell
基于Web API的自动化信息收集和整理
【4月更文挑战第30天】
19 0
|
13天前
|
开发框架 缓存 前端开发
利用Visual Basic构建高效的ASP.NET Web应用
【4月更文挑战第27天】本文探讨使用Visual Basic与ASP.NET创建高效Web应用的策略,包括了解两者基础、项目规划、MVC架构、数据访问与缓存、代码优化、异步编程、安全性、测试及部署维护。通过这些步骤,开发者能构建出快速、可靠且安全的Web应用,适应不断进步的技术环境。
|
1天前
|
XML 开发框架 .NET
C#/ASP.NET应用程序配置文件app.config/web.config的增、删、改操作
C#/ASP.NET应用程序配置文件app.config/web.config的增、删、改操作
|
12天前
|
JSON 安全 API
【专栏】四种REST API身份验证方法:基本认证、OAuth、JSON Web Token(JWT)和API密钥
【4月更文挑战第28天】本文探讨了四种REST API身份验证方法:基本认证、OAuth、JSON Web Token(JWT)和API密钥。基本认证简单但不安全;OAuth适用于授权第三方应用;JWT提供安全的身份验证信息传递;API密钥适合内部使用。选择方法时需平衡安全性、用户体验和开发复杂性。
|
8天前
|
关系型数据库 MySQL
web简易开发(二){html5+php实现文件上传及通过关键字搜索已上传图片)}
web简易开发(二){html5+php实现文件上传及通过关键字搜索已上传图片)}
|
2天前
|
前端开发 JavaScript Java
Java与Web开发的结合:JSP与Servlet
Java与Web开发的结合:JSP与Servlet
7 0
|
2天前
|
存储 程序员 API
python web开发示例详解
python web开发示例详解
11 0
|
2天前
|
XML 前端开发 JavaScript
CSR(客户端渲染)和AJAX在Web开发中各自扮演不同的角色
【5月更文挑战第8天】CSR(客户端渲染)与AJAX在Web开发中各司其职。CSR提供初始HTML框架,通过JavaScript在浏览器端获取并渲染数据,提升交互性和响应速度。AJAX则实现页面局部更新,如实时搜索,不刷新页面即可获取数据。CSR可能因DOM操作多而引发性能问题,但可优化解决;AJAX适合频繁交互场景,提高响应性。两者在不同需求下各有优势,需按项目选择适用技术。
12 4
|
2天前
|
前端开发 搜索推荐 安全
AJAX和CSR(客户端渲染)是Web开发中常用的两种技术
【5月更文挑战第8天】AJAX提升用户体验,减轻服务器压力,但对搜索引擎不友好且增加开发复杂度,易引发安全问题。CSR提供快速响应和交互性,改善用户体验,但首屏加载慢,搜索引擎支持不足,同样面临安全挑战。两者各有适用场景,需按项目需求选择。
9 0