HttpRequestMessage 没有将 Cookie 添加到请求中

HttpRequestMessage doesn't add Cookie into request

我从我的控制台应用程序通过 HttpClient 发出一个简单的 POST 请求

HttpRequestMessage requestMessage = new HttpRequestMessage { Method = method };
requestMessage.Headers.Add("custom1", "c1");
requestMessage.Headers.Add("custom2", "c2");
requestMessage.Headers.Add("Cookie", "c3");
HttpClient client = new HttpClient();
using (var response = await client.SendAsync(requestMessage, cancellationToken))
using (var responseStream = await response.Content.ReadAsStreamAsync())
{
    //...
}

当我在 Fiddler 中看到请求 Headers 时,我只看到前两个 header - custom1 和 custom2,没有 "Cookie" header .

我使用 VS2017 和 .NET 4.7

您不应该通过简单地添加 header 来添加 cookie,因为 CookieContainerHttpCookie 会为您处理一些事情,例如过期、路径、域和为 cookie 设置名称和值的正确方法。

更好的方法是使用CookieContainer

var baseAddress = new Uri('http://localhost');

HttpRequestMessage requestMessage = new HttpRequestMessage { Method = method };
requestMessage.Headers.Add("custom1", "c1");
requestMessage.Headers.Add("custom2", "c2");
// requestMessage.Headers.Add("Cookie", "c3"); wrong way to do it

var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
{
   using(HttpClient client = new HttpClient(handler) { BaseAddress = baseAddress })
   {
       cookieContainer.Add(baseAddress, new Cookie("CookieName", "cookie_value"));
       using (var response = await client.SendAsync(requestMessage, cancellationToken))
       using (var responseStream = await response.Content.ReadAsStreamAsync())
       {
              // do your stuff
       }
   }
}

Off-topic推荐:

不要每次都创建新的 HttpClient 实例。这将导致所有套接字都忙。请遵循更好的方法,例如单例或 HttpClientFactory.