I have a static httpclient shared across requests and I want to add one custom header to it.
httpClient.DefaultRequestHeaders.Add("customHeader", somevalue.ToString());
But I noticed that on every request the value is getting added to that header which I intend to replace on each request. I try to remove the header if it is already exist and add again but it gives me an errors on 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 custom header value on each request?
The DefaultRequestHeaders property returns an HttpRequestHeaderCollection object that can be used to get or set the specific headers on the HttpClient instance.
In the Home pane, double-click HTTP Response Headers. In the HTTP Response Headers pane, click Add... in the Actions pane. In the Add Custom HTTP Response Header dialog box, set the name and value for your custom header, and then click OK.
The error I was getting: An item with the same key has already been added. Key: x
Example code for mahesh_ing 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With