大多数自定义请求的属性都是在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>
书中说,当我们调用HttpClient
的SendAsync
方法时,会调用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。非同步