C# 如何在 HttpClient 的 HttpRequestMessage 上设置 cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12373738/
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 do I set a cookie on HttpClient's HttpRequestMessage
提问by George Mauer
I am trying to use the web api's HttpClientto do a post to an endpoint that requires login in the form of an HTTP cookie that identifies an account (this is only something that is #ifdef'ed out of the release version).
我正在尝试使用 web apiHttpClient向需要以标识帐户的 HTTP cookie 形式登录的端点发布帖子(这只是#ifdef发布版本之外的内容)。
How do I add a cookie to the HttpRequestMessage?
如何将 cookie 添加到HttpRequestMessage?
采纳答案by Darin Dimitrov
Here's how you could set a custom cookie value for the request:
以下是为请求设置自定义 cookie 值的方法:
var baseAddress = new Uri("http://example.com");
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("foo", "bar"),
new KeyValuePair<string, string>("baz", "bazinga"),
});
cookieContainer.Add(baseAddress, new Cookie("CookieName", "cookie_value"));
var result = await client.PostAsync("/test", content);
result.EnsureSuccessStatusCode();
}
回答by Greg Beech
The accepted answeris the correct way to do this in most cases. However, there are some situations where you want to set the cookie header manually. Normally if you set a "Cookie" header it is ignored, but that's because HttpClientHandlerdefaults to using its CookieContainerproperty for cookies. If you disable that then by setting UseCookiesto falseyou can set cookie headers manually and they will appear in the request, e.g.
在大多数情况下,接受的答案是正确的方法。但是,在某些情况下,您需要手动设置 cookie 标头。通常,如果您设置“Cookie”标头,它会被忽略,但这是因为HttpClientHandler默认情况下使用其CookieContainer属性来处理 cookie。如果您禁用它,那么通过设置UseCookies为false您可以手动设置 cookie 标头,它们将出现在请求中,例如
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();
}
回答by Amir No-Family
After spending hours on this issue, none of the answers above helped me so I found a really useful tool.
在这个问题上花了几个小时后,上面的答案都没有帮助我,所以我找到了一个非常有用的工具。
Firstly, I used Telerik's Fiddler 4 to study my Web Requests in details
首先,我使用 Telerik 的 Fiddler 4 详细研究了我的 Web 请求
Secondly, I came across this useful plugin for Fiddler:
其次,我遇到了这个对 Fiddler 有用的插件:
https://github.com/sunilpottumuttu/FiddlerGenerateHttpClientCode
https://github.com/sunilpottumuttu/FiddlerGenerateHttpClientCode
It will just generate the C# code for you. An example was:
它只会为您生成 C# 代码。一个例子是:
var uriBuilder = new UriBuilder("test.php", "test");
var httpClient = new HttpClient();
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, uriBuilder.ToString());
httpRequestMessage.Headers.Add("Host", "test.com");
httpRequestMessage.Headers.Add("Connection", "keep-alive");
// httpRequestMessage.Headers.Add("Content-Length", "138");
httpRequestMessage.Headers.Add("Pragma", "no-cache");
httpRequestMessage.Headers.Add("Cache-Control", "no-cache");
httpRequestMessage.Headers.Add("Origin", "test.com");
httpRequestMessage.Headers.Add("Upgrade-Insecure-Requests", "1");
// httpRequestMessage.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
httpRequestMessage.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
httpRequestMessage.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
httpRequestMessage.Headers.Add("Referer", "http://www.translationdirectory.com/");
httpRequestMessage.Headers.Add("Accept-Encoding", "gzip, deflate");
httpRequestMessage.Headers.Add("Accept-Language", "en-GB,en-US;q=0.9,en;q=0.8");
httpRequestMessage.Headers.Add("Cookie", "__utmc=266643403; __utmz=266643403.1537352460.3.3.utmccn=(referral)|utmcsr=google.co.uk|utmcct=/|utmcmd=referral; __utma=266643403.817561753.1532012719.1537357162.1537361568.5; __utmb=266643403; __atuvc=0%7C34%2C0%7C35%2C0%7C36%2C0%7C37%2C48%7C38; __atuvs=5ba2469fbb02458f002");
var httpResponseMessage = httpClient.SendAsync(httpRequestMessage).Result;
var httpContent = httpResponseMessage.Content;
string result = httpResponseMessage.Content.ReadAsStringAsync().Result;
Note that I had to comment out two lines as this plugin is not totally perfect yet but it did the job nevertheless.
请注意,我不得不注释掉两行,因为这个插件还不完全完美,但它仍然完成了工作。
DISCLAIMER: I am not associated or endorsed by either Telerik or the plugin's author in anyway.
免责声明:无论如何,我与 Telerik 或插件作者都没有关联或认可。
回答by Waqar UlHaq
For me the simple solution works to set cookies in HttpRequestMessageobject.
对我来说,简单的解决方案可以在HttpRequestMessage对象中设置 cookie 。
protected async Task<HttpResponseMessage> SendRequest(HttpRequestMessage requestMessage, CancellationToken cancellationToken = default(CancellationToken))
{
requestMessage.Headers.Add("Cookie", $"<Cookie Name 1>=<Cookie Value 1>;<Cookie Name 2>=<Cookie Value 2>");
return await _httpClient.SendAsync(requestMessage, cancellationToken).ConfigureAwait(false);
}

