Question

HttpClient has a convenience property DefaultRequestHeaders which defines default headers to be included in any request.

I'm trying to apply this to the batching support in Web API, but I've noticed that these default headers are not applied to multi-part HttpMessageContent requests:

var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-Some-Header, "foobar");

var batchContent = new MultipartContent("mixed");

foreach(var x in something)
{
    // these inner requests don't get default headers.
    HttpRequestMessage msg = MakeRequestFromSomething(x);
    batchContent.Add(new HttpMessageContent(msg));
}

// only this outer one does.
var results = await client.PostAsync("/batch", batchContent);

This behavior makes sense, but I'm still looking for a way to apply the headers to the inner requests. Does HttpClient or Web API have anything to make doing so cleaner than manually clearing the request's headers and replacing them with the client's defaults?

Was it helpful?

Solution

You could add the following inside your loop after creating the msg,

foreach (var header in client.DefaultRequestHeaders)
{
     msg.Headers.Remove(header.Key);
     msg.Headers.TryAddWithoutValidation(header.Key, header.Value);
}

This will merge the default headers into the message headers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top