Update custom header value added as DefaultRequestHeaders HttpClient

I have a static httpclient common to requests, and I want to add one custom header to it.

httpClient.DefaultRequestHeaders.Add("customHeader", somevalue.ToString()); 

But I noticed that for each request, a value is added to this header, which I intend to replace with each request. I am trying to remove the header if it already exists and add it again, but it gives me errors in the load test .

 if (httpClient.DefaultRequestHeaders.Contains("customHeader")) { httpClient.DefaultRequestHeaders.Remove("customHeader"); } httpClient.DefaultRequestHeaders.Add("customHeader",somevalue.ToString()); 

Errors -

 System.ArgumentException: An item with the same key has already been added. System.InvalidOperationException: Collection was modified; enumeration operation may not execute. System.ArgumentNullException: Value cannot be null. 

How can I update the value of the custom header for each request?

+6
source share
2 answers

I added a header to the current (current) request using HttpRequestMessage and replaced the call with SendAsync instead of GetAsync, and it solved my problem. Thanks @levent.

+1
source

The error I received was: An item with the same key has already been added. Key: x An item with the same key has already been added. Key: x

Sample code for mahesh_ing's answer:

 var request = new HttpRequestMessage { Method = this.method, RequestUri = new Uri(this.requestUri), }; request.Headers.Add("Key", "Value"); var client = new System.Net.Http.HttpClient { Timeout = this.timeout }; return await client.SendAsync(request); 
0
source

Source: https://habr.com/ru/post/1014870/


All Articles