0
我想在我的webapi中编写自定义批处理程序。asp.net webapi中的自定义批处理程序
对此的要求:我无法识别传入请求是批处理或独立的一部分的天气。
通过编写自定义批处理程序,我将能够在每个请求的标题中添加值,我可以稍后使用它来标识。
我想在我的webapi中编写自定义批处理程序。asp.net webapi中的自定义批处理程序
对此的要求:我无法识别传入请求是批处理或独立的一部分的天气。
通过编写自定义批处理程序,我将能够在每个请求的标题中添加值,我可以稍后使用它来标识。
首先,我们需要编写自定义批处理hahttps://stackoverflow.blog/2011/07/01/its-ok-to-ask-and-answer-your-own-questions/ndler 为此,我们需要覆盖HttpMessageHandler。下面是在上面的代码代码
public class BatchHandler : HttpMessageHandler
{
HttpMessageInvoker _server;
public BatchHandler(HttpConfiguration config)
{
// BatchServer is a class which overrides
_server = new HttpMessageInvoker(new BatchServer(config));
}
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
// Return 400 for the wrong MIME type
// As batch request will always be of MIME type
if ("multipart/mixed" !=
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();
innerReq.Headers.Add("IsBatch", "true");
// Send the request through the pipeline
innerResp = await _server.SendAsync(
innerReq,
cancellationToken
);
}
catch (Exception ex)
{
// 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;
}
}
他们是这条线
// BatchServer is a class which overrides HttpServer
_server = new HttpMessageInvoker(new BatchServer(config));
,如果我们不这样做,我们会得到一个错误
的“DelegatingHandler名单是无效的,因为property 'xxhandler'的'InnerHandler'不为null。\ r \ n参数 名称:处理程序
下面是BatchServer类覆盖的HttpServer
public class BatchServer : HttpServer
{
private readonly HttpConfiguration _config;
public BatchServer(HttpConfiguration configuration)
: base(configuration)
{
_config = configuration;
}
protected override void Initialize()
{
var firstInPipeline = _config.MessageHandlers.FirstOrDefault();
if (firstInPipeline != null && firstInPipeline.InnerHandler != null)
{
InnerHandler = firstInPipeline;
}
else
{
base.Initialize();
}
}
}
现在我们想打BatchHandler 批量要求为此,我们需要配置路由BatchHandler 添加下面的代码到你的AppStart的
var batchHandler = new BatchHandler(config);
config.Routes.MapHttpRoute("batch", "api/batch", null, null, batchHandler);