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 the
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.
While looking for an answer to another problem I have with the NetworkCredentials I stumbled across two questions with answers that might be the ones you're looking for:
Here the answer says that at least WebRequest has the default behaviour of only sending the credentials after getting a 401. And here it seems that the solution might be using a CredentialCache.
I'm not sure if the CredentialCache works with the HttpClient, but if it doesn't you could switch to WebRequest or also WebClient, or maybe this information just brought you on the path to another solution.
You could try setting HttpClientHandler.PreAuthenticate as per Tobberoth's answer, although the documentation for that suggests it will only help after the very first request:
With the exception of the first request, the PreAuthenticate property indicates whether to send authentication information with subsequent requests to a Uri that matches the specific Uri up to the last forward slash without waiting to be challenged by the server.
It won't help for the very first request, but it may help to reduce the number of round trips after that.
Another thing to try is including "Authorization" in HttpClient.DefaultRequestHeaders. I'd be slightly surprised if that worked, but it's worth trying, at least.
The best to avoid the second call is to create and set Authorization header manually: https://stackoverflow.com/a/4346843/1143824