I'm connecting to an API, whos' owner doesn't allow more than 1 request per connection. This is very unfortunate, but I have to work with this. I could create a new HttpClient for each request, but this would leave me vulnerable for socket exhaustion. As such, I'm setting for my HttpClient:
DefaultRequestHeaders.ConnectionClose = true;
And getting it from IHttpClientFactory via
_httpClientFactory.CreateClient();
Now this mostly works fine, but there is one issue. If I send subsequent calls in a loop, like so:
for (int i = 0; i < 10; i++)
{
var request = _requestBuilder.BuildRequest();
var httpClient = _httpClientFactory.CreateClient();
var response = await httpClient.SendAsync(request);
}
Then this will sometimes fail trying to reuse the old connection before it's closed. So my first question is: why is IHttpClientFactory reusing the old connection if I send the request with a Connection: close header?
What's more, I've been looking at netstat and while, unsuprisingly, after creating a new HttpClient for each call I get a bunch of connections in TIME_WAIT status. But for the above ,if it doesn't fail, I get a single connection in CLOSE_WAIT. If I query netstat during runtime of these requests I can see the port is being changed for the current connection, but if a new connection is opened the old one is closed immediately and it doesn't hang in any status. So how is the IHttpClientFactory actually managing this? I couldn't get to close the connection immediately by calling dispose on either HttpClient or HttpResponseMessage
