简体   繁体   中英

Why second HttpClient.PostAsync returns 500?

In the following code I receive 200 in the first request and 500 for all after that. I am new to .Net Core C# so I learned I should assign certain HttpClient attributes only once ie timeout.

However, my automated tests are successful first time but 500 after that. I am using 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);

I found the issue with the code. I should have created a new instance of the HttpClient using the HttpClientFactory for every Http request:

_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
        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM