提问者:小点点

如何在 HttpClient 的 HttpRequestMessage 上设置 Cookie


我正在尝试使用 Web API 的 HttpClient 向需要以标识帐户的 HTTP cookie 形式登录的endpoint发布帖子(这只是发布版本中#ifdef的内容)。

如何向 HttpRequestMessage 添加 Cookie?


共3个答案

匿名用户

下面介绍了如何为请求设置自定义 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();
}

匿名用户

在大多数情况下,接受的答案是正确的方法。但是,在某些情况下,您需要手动设置 cookie 标头。通常,如果您设置了“Cookie”标头,则会忽略它,但这是因为 HttpClientHandler 默认将其 CookieContainer 属性用于 cookie。如果您禁用它,那么通过将 UseCookie 设置为 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();
}

匿名用户

对我来说,简单的解决方案可以在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);
}