Applying default headers to multi-part request con

2019-08-12 12:46发布

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?

1条回答
放我归山
2楼-- · 2019-08-12 13:24

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.

查看更多
登录 后发表回答