【问题标题】:HttpRequestMessage doesn't add Cookie into requestHttpRequestMessage 不会将 Cookie 添加到请求中
【发布时间】:2019-06-29 19:54:34
【问题描述】:

我从控制台应用程序通过 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 中看到请求标头时,我只看到前两个标头 - custom1 和 custom2,没有“Cookie”标头。

我使用 VS2017 和 .NET 4.7

【问题讨论】:

标签: c# network-programming httpclient dotnet-httpclient


【解决方案1】:

您不应仅通过添加标头来添加 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
       }
   }
}

题外话推荐

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

【讨论】:

  • 为什么使用 CookieContainer 比添加标题更正确?感谢 HttpClientFactory 尽管它与 .NET Core 相关
  • @amplifier 因为使用 CookieContainer,您可以轻松处理过期、路径、域 而不必担心do I need to escape or encode the name or value for cookies?。查看 MDN 上的 Set-Cookie 标头。是的 HttpClientFactory 是一个 .NET Core 的东西,但不要忘记你应该让你的 HttpClient 实例单调。
猜你喜欢
  • 2012-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-23
  • 1970-01-01
  • 2017-09-22
  • 2020-02-22
相关资源
最近更新 更多