本文介绍了如何在 HttpClient 的 HttpRequestMessage 上设置 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).
如何向 HttpRequestMessage
添加 cookie?
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 = await client.PostAsync("/test", content);
result.EnsureSuccessStatusCode();
}
这篇关于如何在 HttpClient 的 HttpRequestMessage 上设置 cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!