
在消息处理程序中,一系列消息处理程序链接在一起。第一个处理程序接收 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 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;
}
} 委托处理程序还可以跳过内部处理程序并直接创建响应。
家电公司网站源码是一个以米拓为核心进行开发的家电商城网站模板,程序采用metinfo5.3.9 UTF8进行编码,软件包含完整栏目与数据。安装方法:解压上传到空间,访问域名进行安装,安装好后,到后台-安全与效率-数据备份还原,恢复好数据后到设置-基本信息和外观-电脑把网站名称什么的改为自己的即可。默认后台账号:admin 密码:132456注意:如本地测试中127.0.0.1无法正常使用,请换成l
示例
public class CustomMessageHandler: DelegatingHandler{
protected override Task 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();
taskCompletion.SetResult(response);
return taskCompletion.Task;
}
}









