How do I set a cookie on HttpClient's HttpRequestMessage

I am trying to use the web api's HttpClient to do a post to an endpoint that requires login in the form of an HTTP cookie that identifies an account (this is only something that is #ifdef'ed out of the release version).

How do I add a cookie to the HttpRequestMessage?

Here's how you could set a custom cookie value for the request:

var baseAddress = new Uri("http://example.com");
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
    var content = new FormUrlEncodedContent(new[]
    {
        new KeyValuePair<string, string>("foo", "bar"),
        new KeyValuePair<string, string>("baz", "bazinga"),
    });
    cookieContainer.Add(baseAddress, new Cookie("CookieName", "cookie_value"));
    var result = await client.PostAsync("/test", content);
    result.EnsureSuccessStatusCode();
}

HttpClient 4, A very important element is the domain being set on the cookie – without setting the proper domain, the client will not send the cookie at all! 2.2. The cookie management API of HttpClient can co-exist with the manual cookie handling. One can manually set request Cookie headers or process response Set-Cookie headers in addition or instead of the automatic cookie management.

The accepted answer is the correct way to do this in most cases. However, there are some situations where you want to set the cookie header manually. Normally if you set a "Cookie" header it is ignored, but that's because HttpClientHandler defaults to using its CookieContainer property for cookies. If you disable that then by setting UseCookies to false you can set cookie headers manually and they will appear in the request, e.g.

var baseAddress = new Uri("http://example.com");
using (var handler = new HttpClientHandler { UseCookies = false })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
    var message = new HttpRequestMessage(HttpMethod.Get, "/test");
    message.Headers.Add("Cookie", "cookie1=value1; cookie2=value2");
    var result = await client.SendAsync(message);
    result.EnsureSuccessStatusCode();
}

[HOWTO] Set Cookie Header on DefaultRequestHeaders of HttpClient, We then tried to manually add the Cookie header with the session token as value to the DefaultRequestHeaders of the HttpClient as follows. 1. 2. Then, we can set up this cookie store on the HttpClient using the setDefaultCookieStore () method and send the request: @Test. public void whenSettingCookiesOnTheHttpClient_thenCookieSentCorrectly() throws ClientProtocolException, IOException {. BasicCookieStore cookieStore = new BasicCookieStore ();

After spending hours on this issue, none of the answers above helped me so I found a really useful tool.

Firstly, I used Telerik's Fiddler 4 to study my Web Requests in details

Secondly, I came across this useful plugin for Fiddler:

https://github.com/sunilpottumuttu/FiddlerGenerateHttpClientCode

It will just generate the C# code for you. An example was:

        var uriBuilder = new UriBuilder("test.php", "test");
        var httpClient = new HttpClient();


        var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, uriBuilder.ToString());



        httpRequestMessage.Headers.Add("Host", "test.com");
        httpRequestMessage.Headers.Add("Connection", "keep-alive");
     //   httpRequestMessage.Headers.Add("Content-Length", "138");
        httpRequestMessage.Headers.Add("Pragma", "no-cache");
        httpRequestMessage.Headers.Add("Cache-Control", "no-cache");
        httpRequestMessage.Headers.Add("Origin", "test.com");
        httpRequestMessage.Headers.Add("Upgrade-Insecure-Requests", "1");
    //    httpRequestMessage.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
        httpRequestMessage.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
        httpRequestMessage.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
        httpRequestMessage.Headers.Add("Referer", "http://www.translationdirectory.com/");
        httpRequestMessage.Headers.Add("Accept-Encoding", "gzip, deflate");
        httpRequestMessage.Headers.Add("Accept-Language", "en-GB,en-US;q=0.9,en;q=0.8");
        httpRequestMessage.Headers.Add("Cookie", "__utmc=266643403; __utmz=266643403.1537352460.3.3.utmccn=(referral)|utmcsr=google.co.uk|utmcct=/|utmcmd=referral; __utma=266643403.817561753.1532012719.1537357162.1537361568.5; __utmb=266643403; __atuvc=0%7C34%2C0%7C35%2C0%7C36%2C0%7C37%2C48%7C38; __atuvs=5ba2469fbb02458f002");


        var httpResponseMessage = httpClient.SendAsync(httpRequestMessage).Result;

        var httpContent = httpResponseMessage.Content;
        string result = httpResponseMessage.Content.ReadAsStringAsync().Result;

Note that I had to comment out two lines as this plugin is not totally perfect yet but it did the job nevertheless.

DISCLAIMER: I am not associated or endorsed by either Telerik or the plugin's author in anyway.

HttpClient - HttpClient Cookie Guide, It is also possible to manually set cookies to be sent to the server. Unfortunately, there are several at times conflicting standards for handling Cookies: the Netscape� Normally if you set a "Cookie" header it is ignored, but that's because HttpClientHandlerdefaults to using its CookieContainerproperty for cookies. If you disable that then by setting UseCookiesto falseyou can set cookie headers manually and they will appear in the request, e.g. var baseAddress = new Uri("http://example.com");

For me the simple solution works to set cookies in HttpRequestMessage object.

protected async Task<HttpResponseMessage> SendRequest(HttpRequestMessage requestMessage, CancellationToken cancellationToken = default(CancellationToken))
{
    requestMessage.Headers.Add("Cookie", $"<Cookie Name 1>=<Cookie Value 1>;<Cookie Name 2>=<Cookie Value 2>");

    return await _httpClient.SendAsync(requestMessage, cancellationToken).ConfigureAwait(false);
}

Working with Cookies in Web API and HttpClient, How to set cookies from a client application (HttpClient) and read those cookies in a Web API controller. Setting cookie from Web API controller� This way the HttpClient object uses the handler object to store cookies. The BaseAddress property of the HttpClient is set to the base address of the Web API. Make sure to change this address to reflect your development environment. Then GetAsync () method of HttpClient is used to invoke the Get () Web API method.

How to add Cookies in Http Client headers from a list of name value , (about 70 js files in total), and each of the JavaScript could set different cookies . In order to use HTTP client to post the data to the web server,� Use Cookie Authentication with Web API and HttpClient. Recently I wrote this article explaining the cookie authentication in ASP.NET Core. A reader asked whether cookie authentication can be used with ASP.NET Core Web API and that too when the Web API is being consumed using HttpClient component.

C# request sending cookie with request using httpclient, C#, //Rextester.Program.Main is the entry point for your code. Don't change it. // Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5 using� When using the HttpClient from System.Net.Http there are two possibilites to do that. Either by passing a HttpClientHandler with a CookieContainer to the HttpClient, which then automatically handles cookies (See here), or by manually handle them. As we create a new instance of the HttpClient in our wrapper for every request, we had to go for

Apache HttpClient - Cookies Management, Here, we created a cookie store, a bunch of cookies by setting the domain and path values, and added these to the cookie store. import org.apache.http.client. To add cookies to a request, populate the cookie container before the request with CookieContainer.Add (uri, cookie). After the request is made the cookie container will automatically be populated with all the cookies from the response. You can then call GetCookies () to retreive them. CookieContainer cookies = new CookieContainer(); HttpClientHandler handler = new HttpClientHandler(); handler.CookieContainer = cookies; HttpClient client = new HttpClient(handler); HttpResponseMessage

Comments
  • handler may be removed from using statement, it will be disposed when http client is disposed.
  • Kimi is correct, but also you should not wrap your HttpClient in a using. aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong
  • CAUTION: if you use just 1 instance of HttpClient to do several requests, cookies using CookieContainer is going cached. Is dangerous to a user get the cookie from another user.
  • "HttpClient is intended to be instantiated once and re-used throughout the life of an application. Especially in server applications, creating a new HttpClient instance for every request will exhaust the number of sockets available under heavy loads..." From here: asp.net/web-api/overview/advanced/…
  • @SergeyT so what does one do when he needs to make separate-session calls to the same resource? :)
  • I've been chasing for several days an error in which requests sent with SendAsync did not send the cookie header; this helped me realize that, unless you set UseCookies = false in the Handler, it will not only use the CookieContainer, but also silently ignore any Cookie stored in the request headers! Thank you so much!
  • This answer is extremely helpful for anyone trying to use HttpClient as a proxy!
  • Trying this now... if it works... you deserve a good ol' Canadian hug.
  • CAUTION: if you use just 1 instance of HttpClient to do several requests, cookies using CookieContainer is going cached. Is dangerous to a user get the cookie from another user.
  • That stupid thing should throw an exception when someone tries to add a "Cookie" header instead of silently loosing it. Cost me an hour of my life. Thanks for the solution.
  • This is essentially the same answer as this one, the only part of it that has to do with cookies is that last addition of a header. Note all the caveats in that answer
  • Note that the accepted answer does a ton more and handles a lot more edge conditions than this. It can be used to do things like http only or scoped cookies, multivalue cookies, etc etc. The second highest rated answer proposes the same method as this but with a lot more context and explanation
  • @GeorgeMauer may be you are right. Both of them creating httpClient from "HttpClient(handler)". In my case I'm creating _httpClient from httpClientPool.GetOrCreateHttpClient()
  • But you don't actually show that in your answer nor explain the difference or the benefits (it also is not actually the question, but I'm not worried about that). I'm not trying to be rude, its just important to be clear who this answer would be helpful to that would not be better helped by the others.