标头不起作用 [英] Headers not working
问题描述
你好:
当我尝试将Cookie标头添加到HttpRequestMessage时,似乎已经添加了它,但是在发送请求时却没有发送它.
When I try to add a Cookie header to a HttpRequestMessage, it seems to be added, but it is not sent when the request is sent.
如果我将标题的名称从"Cookie"更改为到另一个随机字符串,就可以了.
If I change the header´s name from "Cookie" to another random string, it works.
HttpClient client = new HttpClient();
HttpRequestMessage msg = new HttpRequestMessage(HttpMethod.Post, "https://.com/post");
msg.Headers.Add("Cookie", "PHPSESSID=" + id);
msg.Content = new StringContent("content");
HttpResponseMessage msg2 = client.SendAsync(msg).Result;
string a = ASCIIEncoding.ASCII.GetString(msg2.Content.ReadAsByteArrayAsync().Result);
我正在使用http://posttestserver.com/post.php检查响应.
I am checking the response using http://posttestserver.com/post.php.
发生了什么事?
谢谢
推荐答案
Hi alecamar,
>>如果我将标题的名称从"Cookie"更改为到另一个随机字符串,就可以了.
>>If I change the header´s name from "Cookie" to another random string, it works.
根据您的消息,我想知道您是否设置了"Cookie"标头被忽略,这是因为
HttpClientHandler
默认将其CookieContainer
属性用于cookie.如果您禁用它,则通过设置
UseCookies
到false
,您可以手动设置Cookie标头,它们将显示在请求中,例如
From your message, I wonder if you set a "Cookie" header it is ignored, that's because
HttpClientHandler
defaults to using its CookieContainer
property for cookies. If you disable that then by setting
UseCookies
to false
you can set cookie headers manually and they will appear in the request, e.g.
var baseAddress = new Uri("http://example.com");
using (var handler = new HttpClientHandler { UseCookies = false })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
var message = new HttpRequestMessage(HttpMethod.Get, "/test");
message.Headers.Add("Cookie", "cookie1=value1; cookie2=value2");
var result = await client.SendAsync(message);
result.EnsureSuccessStatusCode();
}
有关更多详细信息,建议您查看 如何在HttpClient的HttpRequestMessage上设置Cookie
For more details, I would suggest you have a look at How do I set a cookie on HttpClient's HttpRequestMessage
希望有帮助!
最诚挚的问候,
克里斯汀
这篇关于标头不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!