0

I make a simple POST request via HttpClient from my Console applications

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())
{
    //...
}

When I see Request Headers in Fiddler, I only see the first two headers - custom1 and custom2, and no "Cookie" header.

I use VS2017 and .NET 4.7

amplifier
  • 1,793
  • 1
  • 21
  • 55

1 Answers1

2

You shouldn't add cookies with simply adding a header because there are things that CookieContainer and HttpCookie will handle for you, things such as Expiration, Path, Domain and correct way of setting name and values for cookies.

The better way is to use 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 recommendation:

DO NOT create a new instance of HttpClient every time. It will cause all sockets get busy. Please follow better approaches like singleton or HttpClientFactory.

Ali Bahrami
  • 5,935
  • 3
  • 34
  • 53
  • Why the use of CookieContainer is the correct way compared to adding headers? And thank you regarding HttpClientFactory although it is related to .NET Core – amplifier Jun 30 '19 at 21:03
  • @amplifier Because with CookieContainer you can easily take care of expiration, path, domain **and not be worried about `do I need to escape or encode the name or value for cookies?`**. Take a look at [Set-Cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie) header on MDN. And yes HttpClientFactory is a .NET Core thing but don't forget that YOU SHOULD MAKE YOUR `HttpClient` instance singletone. – Ali Bahrami Jul 01 '19 at 04:18