【问题标题】:Understanding SendAsync method ASP.net web API Message Handlers了解 SendAsync 方法 ASP.net Web API 消息处理程序
【发布时间】:2016-11-24 13:23:20
【问题描述】:

我正在尝试实现一个自定义消息处理程序,下面是代码。

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# 中的任务和异步/等待。 但我无法理解在接收请求和发送响应时如何执行相同的方法。

【问题讨论】:

    标签: asp.net asp.net-web-api asp.net-web-api2


    【解决方案1】:

    This 来自 asp.net 网站并解释了 SendAsync 的工作原理。

    该方法将 HttpRequestMessage 作为输入并异步返回 HttpResponseMessage。典型的实现如下:

    1. 处理请求消息。
    2. 调用 base.SendAsync 将请求发送到内部处理程序。
    3. 内部处理程序返回响应消息。 (这一步是 异步。)
    4. 处理响应并将其返回给调用者。

    这是一个简单的例子:

    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,关于如何使用消息处理程序记录请求和响应消息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-26
      • 1970-01-01
      • 1970-01-01
      • 2013-03-22
      • 2021-04-14
      相关资源
      最近更新 更多