Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 943
George Mauer Avatar asked Sep 11 '12 16:09

George Mauer


People also ask

What is HttpClientHandler C#?

The HttpClient class uses a message handler to process the requests on the client side. The default handler provided by the dot net framework is HttpClientHandler. This HTTP Client Message Handler sends the request over the network and also gets the response from the server.


1 Answers

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(); } 
like image 184
Darin Dimitrov Avatar answered Oct 08 '22 21:10

Darin Dimitrov