为什么第二个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
}
}

最新更新