将默认标头应用于多部分请求内容 [英] Applying default headers to multi-part request content

查看:60
本文介绍了将默认标头应用于多部分请求内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HttpClient 具有一个便捷属性 DefaultRequestHeaders ,它定义了要包含在任何请求中的默认标头。

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

我试图将其应用于Web API中的批处理支持,但是我注意到这些默认标头不适用于多部分 HttpMessageContent 请求:

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);

这种行为很有意义,但我仍在寻找一种将标头应用于内部请求的方法。与手动清除请求的标头并将其替换为客户端的默认值相比,Web API可以使操作更清洁?

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?

推荐答案

在创建msg之后在循环内添加以下内容,

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.

这篇关于将默认标头应用于多部分请求内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆