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
?
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.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With