当HttpClientHandler传递给HttpClient时,调用哪个SendAsync方法



大多数自定义请求的属性都是在HttpClientHandler中定义的,该类是HttpMessageHandler的子类,该类定义如下:

public abstract class HttpMessageHandler : IDisposable
{
  protected internal abstract Task<HttpResponseMessage> SendAsync
    (HttpRequestMessage request, CancellationToken cancellationToken);
  public void Dispose();
  protected virtual void Dispose (bool disposing);
}

<C#5.0 in a nutshell>书中说,当我们调用HttpClientSendAsync方法时,会调用HttpMessageHandler中的SendAsync方法。但是HttpClient类也定义了一个SendAsync方法,当我们在HttpClient的实例上调用这个方法时,哪个SendAsync被调用?

实际情况如下:

HttpMessageInvoker,HttpClient

class HttpMessageInvoker
{
    private HttpMessageHandler handler;
    public HttpMessageInvoker(HttpMessageHandler handler)
    {
        this.handler = handler;
    }
    public virtual void SendAsync()
    {
        Console.WriteLine("HttpMessageInvoker.SendAsync");
        this.handler.SendAsync();
    }
}
class HttpClient : HttpMessageInvoker
{
    public HttpClient(HttpMessageHandler handler)
        : base(handler)
    {
    }
    public override void SendAsync()
    {
        Console.WriteLine("HttpClient.SendAsync");
        base.SendAsync();
    }
}

HttpMessageHandler,HttpClientHandler

abstract class HttpMessageHandler
{
    protected internal abstract void SendAync();
}
class HttpClientHandler : HttpMessageHandler
{
    protected internal override void SendAync()
    {
        Console.WriteLine("HttpClientHandler.SendAsync");
    }
}

如果在HttpClient实例上调用SendAsync,该方法将被执行。该方法从HttpMessageInvoker调用SendAsync方法。这个方法调用HttpMessageHandler实例的SendAsync方法。HttpMessageHandler是抽象的;HttpClientHandler通过覆盖抽象的SendAync方法,提供了一个具体的实现。

例子:

var handler = new HttpClientHandler();
var client = new HttpClient(handler);
client.SendAsync();
输出:

<>之前HttpClient。非同步HttpMessageInvoker。非同步HttpClientHandler。非同步

相关内容

  • 没有找到相关文章

最新更新