在消息处理程序中,一系列消息处理程序链接在一起。第一个处理程序接收 HTTP 请求,进行一些处理,然后将请求交给下一个处理程序。在某个时刻,响应会被创建并返回到链上。这种模式称为委托处理程序。
除了内置的服务器端消息处理程序之外,我们还可以创建自己的服务器端 HTTP 消息处理程序。 创建自定义服务器端 HTTPASP.NET Web API 中的消息处理程序,我们使用DelegatingHandler。我们必须创建一个从System.Net.Http.DelegatingHandler派生的类。然后,该自定义类应重写 SendAsync 方法。
Task SendAsync(HttpRequestMessage request,CancellationToken CancellationToken);
该方法将 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; }}
登录后复制
委托处理程序还可以跳过内部处理程序并直接创建响应。
示例
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; }}
登录后复制
以上就是Asp.Net webAPI C# 中 DelegatingHandler 的用法是什么?的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2429619.html