9

自定义请求的大部分属性都定义在 中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>上说,当我们调用's方法时,就会调用SendAsyncin中的方法。但是类也定义了一个方法,当我们在一个实例上调用这个方法时,调用的是哪个?HttpMessageHandlerHttpClientSendAsyncHttpClientSendAsyncHttpClientSendAsync

4

1 回答 1

6

这就是本质上正在发生的事情:

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");
    }
}

因此,如果您调用SendAsync实例HttpClient,则会执行该方法。该方法SendAsync从 调用该方法HttpMessageInvoker。该方法调用实例的SendAsync方法。是抽象的;通过覆盖抽象方法来提供具体的实现。HttpMessageHandlerHttpMessageHandlerHttpClientHandlerSendAync

例子:

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

输出:

HttpClient.SendAsync
HttpMessageInvoker.SendAsync
HttpClientHandler.SendAsync
于 2013-01-07T08:53:13.683 回答