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
?
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:
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.
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 itsCookieContainer
property for cookies. If you disable that then by settingUseCookies
tofalse
you can set cookie headers manually and they will appear in the request, e.g.Here's how you could set a custom cookie value for the request: