HttpClient in .net issues 2 requests when providing username and password in NetworkCredentials

.net, c#

Solution

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.

Problem

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 }; ```

Original source

Related problems