在发送HttpResponseMessage
请求之后,我试图改善对失败的HttpClient.SendAsync
响应的日志记录。
使用.net-core的System.Net.Http.IHttpClientFactory
feature,此代码发出请求:
POST https // fooApp.fooDomain.com / fooMethod
Content-Type:application / json; charset = utf-8
startup.cs:
services.AddHttpClient("MyHttpClient", client =>
{
client.BaseAddress = new Uri("https//fooApp.fooDomain.com/");
client.Timeout = new TimeSpan(0, 0, 15);
});
MyHttpService.cs:
public class MyHttpService
{
private readonly IHttpClientFactory _factory;
public MyHttpService(IHttpClientFactory factory)
{
_factory = factory;
}
private async Task<HttpResponseMessage> GetHttpResponseMessage(...)
{
try
{
HttpClient httpClient = this._factory.CreateClient("MyHttpClient");
using (request.HttpContent)
{
var requestMessage = new HttpRequestMessage
{
RequestUri = new Uri("fooMethod", UriKind.Relative),
Method = HttpMethod.Post,
Content = new StringContent(string.Empty, Encoding.UTF8, "application/json")
};
using (requestMessage)
{
return await httpClient.SendAsync(requestMessage);
}
}
}
catch (Exception ex)
{
//Log the exception...
return null;
}
}
}
问题是当SendAsync
抛出异常(如TaskCanceledException
或OperationCanceledException
由于超时)时,我想查看取消令牌的IsCancellationRequested
并记录正确的消息,如果为真。
我的问题是创建CancellationToken
并传递到SendAsync
方法中的最佳方法(在哪里)?为了在发生超时时捕获它。据我了解,令牌必须与在启动时初始化的HttpClient
超时时间跨度协调。
try
{
//...
return await httpClient.SendAsync(requestMessage, cts);
}
catch (TaskCanceledException ex)
{
if (cts.IsCancellationRequested) //log time-out
else //log general
}
catch (Exception ex)
{
//log general
}