Applying default headers to multi-part request content

こ雲淡風輕ζ 提交于 2019-12-11 12:06:24

问题


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:


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.



来源:https://stackoverflow.com/questions/21734003/applying-default-headers-to-multi-part-request-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!