Reputation: 5619
I am struggling to understand how to add MULTIPLE headers to the HttpRequestMessage. I mean I get the basics and if I do one header it works but multiple headers and the last one is what sticks and all others are overwritten?
So for example the Accept header will be overwritten but the authorization header will stick.
HttpRequestMessage httpreqmsg = new HttpRequestMessage();
httpreqmsg.Headers.Add("Accept", "CustomAccept");
httpreqmsg.Headers.Add("Authorization", "asdfas#%fwqerq@werfds...");
Now HttpRequestMessage has an overload with the signature
.Add(string, List<string>)
and that is fine if you have ONE name with multiple values but how do you do multiple headers. TryAddWithoutValidation has the same overloads as above?
TIA
Great...so I kinda made a mistake in my post. I didn't think it mattered but it does. I am unit testing a controller and therefore there is no HttpClient object created.
Upvotes: 1
Views: 5375
Reputation: 609
Building on @sidjames's post. It seems you're looking for the Accept and Authorization headers. If that's the case, then set it in HttpClient, instead of the HttpRequestMessage:
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("some accept"));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "your parameters");
There are a bunch of examples for accept and authorization on the StackOverflow.
Upvotes: 2
Reputation: 176
Not sure about the context of your code, but you could use HttpClient (WebApi NuGet) instead, which lets you add "Accept" and "Authorization" headers:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("scheme", "param");
//client.PostAsJsonAsync or something else
}
Upvotes: 3
Reputation: 117
It seems the "Accept" header is reserved. No matter what value I tried to assign to it a FormatException was thrown.
If you change your code to this you get both headers back.
HttpRequestMessage httpreqmsg = new HttpRequestMessage();
httpreqmsg.Headers.Add("Lolz", "CustomAccept");
httpreqmsg.Headers.Add("Authorization", "SomeValue");
foreach (var item in httpreqmsg.Headers)
{
Console.WriteLine(item.Key + " : " + item.Value);
}
Also the value of 'Authorization' in your example was invalid, but I'm guessing that was just random key mashing :)
Upvotes: 3