c# - 使用 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
抛出异常(如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
}
解决方案
推荐阅读
- php - Codeigniter 排除文件和文件夹
- javascript - PropTypes 和 React Context API 语法错误
- r - 解析RShiny selectinput multiple=true
- here-api - NMARoutingErrorNetwork通讯说明
- java - java.lang.AbstractMethodError:org.apache.xerces.jaxp.DocumentBuilderFactoryImpl 不继承抽象 javax.xml.parsers.DocumentBuilderFactory
- docker - 重定向码头工人拉
- c# - 安装版本和调试时的路径有何不同?
- jenkins - 无法找到请求目标的有效认证路径:Jenkins
- python - Python,范围()
- docker - 无法通过警报管理器发送电子邮件