Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating custom header value added as DefaultRequestHeaders of HttpClient

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?

like image 999
mahesh_ing Avatar asked Feb 10 '17 10:02

mahesh_ing


People also ask

What is HttpClient DefaultRequestHeaders?

The DefaultRequestHeaders property returns an HttpRequestHeaderCollection object that can be used to get or set the specific headers on the HttpClient instance.

Can I add custom header to HTTP request?

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.


1 Answers

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);
like image 171
Gerald Hughes Avatar answered Sep 20 '22 12:09

Gerald Hughes