我遇到了一个问题,每隔一段时间(也许每周一次),我注意到没有发出HttpClient的请求。
该过程每5s连续24/5发出两个请求。第一个是POST,第二个是GET。该故障仅在第二个请求上发生,并且每次此周期运行(即每5s)重复一次。
在每次调用时,c#脚本都使用一个IHttpClientFactory(使用Microsoft.Extensions.Http v2.1.0),并使用一个命名实例来检索相关的客户端。
var httpClient = HttpClientFactory.CreateClient("[named_instance]");
services.AddHttpClient("[named_instance]")
.ConfigurePrimaryHttpMessageHandler(() =>
{
return new HttpClientHandler
{
UseCookies = false,
UseDefaultCredentials = false
};
});
POST方法
var httpClient = CreateClient();
httpClient.DefaultRequestHeaders.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var body = $"[json here]";
var content = new StringContent(body, Encoding.UTF8, "application/json");
return await httpClient.PostAsync("[url_here]", content).ConfigureAwait(false);
GET方法
var httpClient = CreateClient();
httpClient.DefaultRequestHeaders.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Add("Authorization", sessionId);
return await httpClient.GetAsync("[url_here]").ConfigureAwait(false);
我已经进行了详细的日志记录(对于HttpClientFactory),并注意到了输出的差异。
工作
Calling Method1
Start processing HTTP request POST https://[url]/[method1]
Sending HTTP request POST https://[url]/[method1]
Received HTTP response after 22.4196ms - OK
End processing HTTP request after 69.3192ms - OK
Calling Method2
Start processing HTTP request GET https://[url]/[method2]
Sending HTTP request GET https://[url]/[method2]
Received HTTP response after 418.6451ms - OK
End processing HTTP request after 459.884ms - OK
错误
Calling Method1
Start processing HTTP request POST https://[url]/[method1]
Sending HTTP request POST https://[url]/[method1]
Received HTTP response after 16.8932ms - OK
End processing HTTP request after 45.3336ms - OK
Calling Method2
No HTTP request made