When using the HttpClient in .net 4.5 to do basic authentication I'm finding that it's issuing 2 requests.
The first fails with a HTTP/1.1 401 Unauthorized and then it resends the request to which we get a HTTP/1.1 200 OK.
Any ideas on how to stop it from doing this?
var credential = new NetworkCredential
{
UserName = username,
Password = password
}
var httpClientHandler = new System.Net.Http.HttpClientHandler
{
Credentials = credential
};
httpClient = new HttpClient(httpClientHandler, true)
{
BaseAddress = address
};
When you use the same instance of HttpClient for multiple requests (sequential and concurrent) to the same URL, it'll reuse connections. Requests that get to reuse a connection are 5.5-8.5x faster than requests that have to open a new connection.
HttpClient is used to send an HTTP request, using a URL. HttpClient can be used to make Web API requests from the console Application, Winform Application, Web form Application, Windows store Application, etc.
Try setting this:
httpClientHandler.PreAuthenticate = true;
I think the very first request will still get the initial 401, but subsequent request to the same URI up to the last forward slash should always send the authentication headers without the 401.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With