C# 如何将标头添加到 httprequestmessage
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13858166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add headers to a httprequestmessage
提问by Dave
I would like to add headers to a HttpRequestMessage. Problem is HttpRequestHeaders has no constructor, HttpHeaders is abstract, ... .
Is there any way we can use these classes somewhere in our code ( I could use a List<Tuple<string, List<string>>but does not look nice at all)
我想向 HttpRequestMessage 添加标头。问题是 HttpRequestHeaders 没有构造函数, HttpHeaders 是抽象的, ... 。有什么方法可以在我们的代码中的某个地方使用这些类(我可以使用 a List<Tuple<string, List<string>>但看起来一点也不好看)
回答by Sjoerd
An HttpRequestMessage already has an instance of HttpRequestHeaders, and you can not change it. You can add a header like this:
一个 HttpRequestMessage 已经有一个 HttpRequestHeaders 的实例,你不能改变它。您可以添加这样的标题:
message.Headers.Add("X-Hello", "world");
回答by Sjoerd
You can get an empty instance of HttpHeadersin one of the following ways:
您可以通过HttpHeaders以下方式之一获取空实例:
var headers = new HttpClient().DefaultRequestHeaders;
var headers = new HttpResponseMessage().Headers;
var headers = new HttpRequestMessage().Headers;
You could also make your own class that extends HttpHeadersand use that.
您还可以创建自己的类来扩展HttpHeaders和使用它。

