I'm trying to set cookies and get cookies from a general method.
I saw this example that works but I'm having troubles in changing my own code in a way that I can keep my general function.
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();
My code:
public static HttpClient CreateClientASMtoken(string tokenVal)
{
var httpClient = new HttpClient
{
BaseAddress = new Uri(urlASM)
};
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//httpClient.DefaultRequestHeaders.Accept.Add(new Cookie("token", tokenVal));
return httpClient;
}
The commented code is one of my trys to make this happen. The other general method that I use is this:
public static async Task<HttpResponseMessage> PostASM(string path, object content)
{
string tokenVal = "d2GpEA5r8pwLRcOPxgaygPooldz2OZ2HUZzZ0YDPAOYCIiH4u5";
using (var client = CreateClientASMtoken(tokenVal))
{
var json = JsonConvert.SerializeObject(content);
var serializedContent = new StringContent(json, Encoding.UTF8, "application/json");
var postResponse = await client.PostAsync(path, serializedContent);
//string response = await postResponse.Content.ReadAsStringAsync();
return postResponse;
}
}
EDIT: I've tried this too:

But it shows an error and the URL is ok and so is the token.
I found a way that solves the problem easily. Thanks for the ones who contributed.
public static async Task<string> GetASM(string path)
{
string tokenVal = "d2GpEA5r8p...";
Uri uriASM = new(urlASM);
var cookieContainer = new CookieContainer();
using var handler = new HttpClientHandler()
{
CookieContainer = cookieContainer,
};
using var client = new HttpClient(handler)
{
BaseAddress = uriASM,
};
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
cookieContainer.Add(uriASM, new Cookie("token", tokenVal));
var getResponse = await client.GetAsync(path);
return await getResponse.Content.ReadAsStringAsync();
}
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