Httpclient This instance has already started one or more requests. Properties can only be modified before sending the first request Httpclient This instance has already started one or more requests. Properties can only be modified before sending the first request asp.net asp.net

Httpclient This instance has already started one or more requests. Properties can only be modified before sending the first request


HttpClient.DefaultRequestHeaders (and BaseAddress) should only be set once, before you make any requests. HttpClient is only safe to use as a singleton if you don't modify it once it's in use.

Rather than setting DefaultRequestHeaders, set the headers on each HttpRequestMessage you are sending.

var request = new HttpRequestMessage(HttpMethod.Post, url);request.Headers.Accept.Clear();request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);request.Content = new StringContent("{...}", Encoding.UTF8, "application/json");var response = await _client.SendAsync(request, CancellationToken.None);

Replace "{...}" with your JSON.


Maybe my two cents will help someone.

I ran into this issue when refreshing the page when debugging the application.

I was using a singleton, but each refresh, it was trying to set the base address. So I just wrapped it in a check to see if the base address had already been set.

The issue for me was, it was trying to set the baseAddress, even though it was already set. You can't do this with a httpClient.

if (_httpClient.BaseAddress == null){    _httpClient.BaseAddress = new Uri(baseAddress);}


The issue is caused by resetting BaseAddress and headers for the same instance of the httpclient.

I tried

if (_httpClient.BaseAddress == null) 

but I am not keen on this.

In my opinion, a better soloution is to use the httpclientFactory. This will terminate and garbage collect the instance of the httpclient after its use.

private readonly IHttpClientFactory _httpClientFactory;public Foo (IHttpClientFactory httpClientFactory) {_httpClientFactory = httpClientFactory;}public  httpresponse Bar (){_httpClient = _httpClientFactory.CreateClient(command.ClientId);using var response = await _httpclient.PostAsync(uri,content);return response;// here as there is no more reference to the _httpclient, the garbage collector will clean // up the _httpclient and release that instance. Next time the method is called a new // instance of the _httpclient is created}