在客户端,HttpClient
使用message handle处理request。默认的handler是HttpClientHandler
,用来发送请求和获取response从服务端。可以在client pipline中插入自定义的message handler:
自定义的message handler:
class MessageHandler1 : DelegatingHandler
{
private int _count = 0;
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
_count++;
request.Headers.Add("X-Custom-Header", _count.ToString());
return base.SendAsync(request, cancellationToken);
}
}
class LoggingHandler : DelegatingHandler
{
StreamWriter _writer;
public LoggingHandler(Stream stream)
{
_writer = new StreamWriter(stream);
}
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
if (!response.IsSuccessStatusCode)
{
_writer.WriteLine("{0} {1} {2}", request.RequestUri,
(int)response.StatusCode, response.Headers.Date);
}
return response;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_writer.Dispose();
}
base.Dispose(disposing);
}
}
将Message Handler添加到Client Pipeline
HttpClient client = HttpClientFactory.Create(new Handler1(), new Handler2(), new Handler3());
Message Handlers调用顺序根据创建时传入的顺序一致,而response消息的传播正好与此相反。