I just encountered this strange behavior, which I can reproduce with the following code:
var request = new HttpRequestMessage(new HttpMethod("POST"), "/api/mymethod");
request.Headers.Add("Cookie", "mycookie");
request.Headers.Add("Cookie2", "mycookie");
request.Content = new StringContent("<foo></foo>", Encoding.UTF8, "application/xml");
return httpClient.SendAsync(request);
I then log the request with necat and I see that Cookie2
is present, but Cookie
is not!
POST /api/mymethod HTTP/1.1
Cookie2: mycookie
Content-Type: application/xml; charset=utf-8
Host: localhost:7777
Content-Length: 11
Expect: 100-continue
Connection: Keep-Alive
<foo></foo>
It seems as if HttpRequestMessage goes out of its way to ignore the Cookie
header, and I am wondering why it behaves like that.
And is there any way to force-add the Cookie? I suppose maybe they do it to enforce good coding practices, but right now I'm making a short throwaway script to automate a manual task (even the cookie is hardcoded in my code) and I was surprised at this behavior.
Found answer:
From https://stackoverflow.com/a/13287224/492336, you can set an HttpClientHandler
with UseCookies
set to false, then it works:
HttpClient httpClient = new HttpClient(new HttpClientHandler { UseCookies = false }) { BaseAddress = new Uri(ConfigurationManager.AppSettings["server"]) };
Anyway, you should probably not use this for non-throwaway code.