7

A bit related to my previous question I have the following:

public static HttpClient client= new HttpClient();
//Basic HTTP client setup
  client.BaseAddress = new Uri(address);
  client.DefaultRequestHeaders.Add("custom_header", "MyCustomHeader");

As you can see I set a base address (the matter of the previous question) that I can not change, and I set a custom header.

My question is can I change later in code this custom header (temporarily or permanently)?

For example I want my requests have the header "MyCustomHeader" but for some particular request, I want it to be "MyOtherHeader".

Is this possible, and if it is, how can I do it?

1
  • what have you tried so fat? ie show us your attempts Commented Oct 15, 2018 at 6:49

1 Answer 1

11

As I understand, you want to add/remove this custom header on runtime.

You can add custom header like code below,

client.DefaultRequestHeaders.Add("custom_header", "MyCustomHeader");

And, you can remove header when you want with code below

client.DefaultRequestHeaders.Remove("custom_header");
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! So if I want to just change , should I remove and add another value?
RequestHeader is KeyValuePair and KeyValuePair Value property is read only. So you should remove and add again with another value.
This of course will affect the default header permanently, is that right? (Until changed back I mean)
You should NOT modify DefaultRequestHeaders at "runtime" (i.e. after initial setup). Think of this scenario: You have a server, and you make/handle two requests at once, one of those requests wants header X and the other wants header Y. If both of those methods (presumably running in separate threads, as is typical for servers) will try to modify the default headers at the same -> you end up with chaos, one or both requests might end up having incorrect headers because they are fighting over what the headers should be! DefaultRequestHeaders should only be used for unchanging headers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.