c# - 为什么第二个 HttpClient.PostAsync 返回 500?
问题描述
在下面的代码中,我在第一个请求中收到 200,之后收到 500。我是新手,.Net Core C#
所以我了解到我应该只分配一次特定的 HttpClient 属性,即超时。
但是,我的自动化测试第一次成功,但之后成功了 500 次。我正在使用 HttpClientFactory。
if (httpClient.Timeout == null)
{
httpClient.Timeout = TimeSpan.FromSeconds(Foo.timeout);
}
if (httpClient.BaseAddress == null) {
httpClient.BaseAddress = new Uri(Foo.url);
}
response = await httpClient.PostAsync("", content);
解决方案
我发现了代码的问题。我应该为每个 Http 请求使用 HttpClientFactory 创建一个新的 HttpClient 实例:
_httpClient = _httpClientFactory.CreateClient(command.ClientId);
public class Foo
{
private readonly IHttpClientFactory _httpClientFactory;
public Foo(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
public async Task<HttpRequestMessage> Bar()
{
var httpClient = _httpClientFactory.CreateClient("Foo");
using var response = await httpClient.PostAsync("example.com", new StringContent("Foo"));
return response.RequestMessage;
// here as there is no more reference to the _httpclient, the garbage
//collector will clean
// up the _httpclient and release that instance. Next time the method is
//called a new
// instance of the _httpclient is created
}
}
推荐阅读
- node.js - 带有 mongoDB 调用 / node.js 的 Foreach 循环
- jquery - AJAX 401(未经授权)
- angularjs - 返回字符串数组的异步 api 的 uib-typeahead 的正确值是多少?
- julia - 如何识别阻止其他软件包更新版本的 julia 软件包?
- c# - Asp.net 核心会话单元测试
- python - 用 RGBA 屏蔽 imshow 或 imshow
- kubernetes - pod 迁移时的 Kubernetes 日志
- mysql - MySQL:如何计算按 day_hour 分组的分钟行
- typescript - 在限制变量类型的同时保持推断类型
- angular - 如何从 Ionic 3 上的 http 帖子中读取 set-cookie 标头