一尘不染

如何在HttpClient的HttpRequestMessage上设置Cookie

c#

我正在尝试使用Web api HttpClient向需要登录的终结点发布帖子,该终结点需要以标识帐户的HTTP
cookie的形式登录(这只是#ifdef发行版本中未包含的内容)。

如何向其中添加Cookie HttpRequestMessage


阅读 567

收藏
2020-05-19

共1个答案

一尘不染

您可以按照以下方法为请求设置自定义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();
}
2020-05-19