使用IHttpClientFactory

时间:2019-11-26 05:57:40

标签: c# multithreading .net-core-3.0

在发送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抛出异常(如TaskCanceledExceptionOperationCanceledException由于超时)时,我想查看取消令牌的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
}

0 个答案:

没有答案