Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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
};
like image 253
Ian Oakes Avatar asked Nov 28 '13 07:11

Ian Oakes


People also ask

Can you reuse HttpClient C#?

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.

What is HttpClient in asp net?

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.


1 Answers

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.

like image 70
Tobberoth Avatar answered Sep 20 '22 15:09

Tobberoth