HttpRequestMessage不会将Cookie添加到请求中

时间:2019-06-29 19:54:34

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

我从控制台应用程序通过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

1 个答案:

答案 0 :(得分:2)

您不应该只添加标题就添加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