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

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
};
Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow