在消息处理程序中,一系列消息处理程序链接在一起。第一个处理程序接收 HTTP 请求,进行一些处理,然后将请求交给下一个处理程序。在某个时刻,响应会被创建并返回到链上。这种模式称为委托处理程序。
除了内置的服务器端消息处理程序之外,我们还可以创建自己的服务器端 HTTP 消息处理程序。 创建自定义服务器端 HTTP ASP.NET Web API 中的消息处理程序,我们使用DelegatingHandler。我们必须创建一个从System.Net.Http.DelegatingHandler派生的类。然后,该自定义类应重写 SendAsync 方法。
Task
该方法将 HttpRequestMessage 作为输入并异步返回 HttpResponseMessage。典型的实现执行以下操作:
- 处理请求消息。
- 调用 base.SendAsync 将请求发送到内部处理程序。
- 内部处理程序返回一条响应消息。 (此步骤是异步的。)
- 处理响应并将其返回给调用者。
示例
'public class CustomMessageHandler : DelegatingHandler{
protected async override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken){
Debug.WriteLine("CustomMessageHandler processing the request");
// Calling the inner handler
var response = await base.SendAsync(request, cancellationToken);
Debug.WriteLine("CustomMessageHandler processing the response");
return response;
}
}
委托处理程序还可以跳过内部处理程序并直接创建响应。
示例
'public class CustomMessageHandler: DelegatingHandler{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken){
// Create the response
var response = new HttpResponseMessage(HttpStatusCode.OK){
Content = new StringContent("Skipping the inner handler")
};
// TaskCompletionSource creates a task that does not contain a delegate
var taskCompletion = new TaskCompletionSource<HttpResponseMessage>();
taskCompletion.SetResult(response);
return taskCompletion.Task;
}
}