我如何设置的HttpClient的Htt的prequestMessage一个cookie [英] How do I set a cookie on HttpClient's HttpRequestMessage
本文介绍了我如何设置的HttpClient的Htt的prequestMessage一个cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图使用Web API的的HttpClient
做了一个帖子,需要在标识帐户的HTTP cookie的形式登录的端点(这仅仅是东西是 #IFDEF
编辑出的发行版)。
I am trying to use the web api's HttpClient
to 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).
我怎么一个cookie添加到的Htt prequestMessage
?
How do I add a cookie to the HttpRequestMessage
?
推荐答案
下面是你如何能为要求设置自定义cookie的值:
Here's how you could set a custom cookie value for the request:
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 = client.PostAsync("/test", content).Result;
result.EnsureSuccessStatusCode();
}
这篇关于我如何设置的HttpClient的Htt的prequestMessage一个cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文