首页 > 解决方案 > 为什么第二个 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);

标签: c#asp.net-core

解决方案


我发现了代码的问题。我应该为每个 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
        }

    }

推荐阅读