Struggling Trying to Get Cookie Out of Response with Httpclient in .Net 4.5

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



Leave a reply



Submit