我正在尝试实现自定义Message Handler,下面是代码。
public class MyHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
/* Code that executes while receiving the request - start */
bool isBadrequest = false;
if (isBadrequest)
{
return request.CreateResponse(System.Net.HttpStatusCode.NotFound,"test");
}
/* Code that executes while receiving the request - end */
/* Code that executes while sending the response - start */
var response = await base.SendAsync(request , cancellationToken);
response.Headers.Add("new header", "new header value");
return response;
/* Code that executes while sending the response - end */
}
}
我知道C#中的Tasks和async / await。 但我无法理解在接收请求和发送响应时如何执行相同的方法。
答案 0 :(得分:2)
This来自asp.net网站,并解释 SendAsync 的工作原理。
该方法将 HttpRequestMessage 作为输入,并异步返回 HttpResponseMessage 。典型的实现如下:
这是一个简单的例子:
public class MessageHandler1 : DelegatingHandler
{
protected async override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
Debug.WriteLine("Process request");
// Call the inner handler.
var response = await base.SendAsync(request, cancellationToken);
Debug.WriteLine("Process response");
return response;
}
}
此外,这里有一个关于如何使用消息处理程序记录请求和响应消息的great article。