Struggling trying to get cookie out of response with HttpClient in .net 4.5
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 response = client.GetAsync("http://google.com").Result;
Uri uri = new Uri("http://google.com");
IEnumerable<Cookie> responseCookies = cookies.GetCookies(uri).Cast<Cookie>();
foreach (Cookie cookie in responseCookies)
Console.WriteLine(cookie.Name + ": " + cookie.Value);
Console.ReadLine();
C# How to pass on a cookie using a shared HttpClient
Instead of calling PutAsJsonAsync() you can use HttpRequestMessage and SendAsync():
Uri requestUri = ...;
HttpMethod method = HttpMethod.Get /*Put, Post, Delete, etc.*/;
var request = new HttpRequestMessage(method, requestUri);
request.Headers.TryAddWithoutValidation("Cookie", ".ASPXAUTH=" + authCookieValue);
request.Content = new StringContent(jsonDataToSend, Encoding.UTF8, "application/json");
var response = await client.SendAsync(request);
UPDATE:
To make sure that your HTTP client does not store any cookies from a response you need to do this:
var httpClient = new HttpClient(new HttpClientHandler() { UseCookies = false; });
Otherwise you might get unexpected behavior by using one client and sharing other cookies.
C# HttpClient GET returns 200 but an empty array
My issue was that the Url
var url = _config["Url"] + $"item?ID={_config["ItemId"]}&DeviceName={_config["DeviceName"]}"
Contained empty new lines, so I had to remove the new lines.
so I added the following to my url.Replace("\n", "").Replace("\r", ""));
HttpResponseMessage httpResponse = await httpClient.GetAsync(url.Replace("\n", "").Replace("\r", ""));```
Related Topics
C#: How to Get an Object by the Name Stored in String
Advantages to Using Private Static Methods
Why Would I Bother to Use Task.Configureawait(Continueoncapturedcontext: False);
ASP.NET Core Appsettings.JSON Update in Code
The Object Cannot Be Deleted Because It Was Not Found in the Objectstatemanager
C# Guid and SQL Uniqueidentifier
How to Load Assembly at Runtime and Create Class Instance
Find Character with Most Occurrences in String
Filter All Queries (Trying to Achieve Soft Delete)
Generate N Random and Unique Numbers Within a Range
Unrolled Loop Works, for Loop Does Not Work
Why Is Try {...} Finally {...} Good; Try {...} Catch{} Bad
Who Should Call Dispose on Idisposable Objects When Passed into Another Object
Set Cultureinfo in ASP.NET Core to Have a . as Currencydecimalseparator Instead of ,