首页 > 解决方案 > 使用 IHttpClientFactory 时如何正确传递取消令牌

问题描述

HttpResponseMessage我正在尝试改进发送HttpClient.SendAsync请求后不成功响应的日志记录。

使用.net-core的System.Net.Http.IHttpClientFactory 功能,此代码发出请求:

POST https//fooApp.fooDomain.com/fooMethod

内容类型:应用程序/json;字符集=utf-8

启动.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
}

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

解决方案


推荐阅读