Using httpclient throughout methods without losing session and cookies
c#
Solution
Your answer is here: https://stackoverflow.com/a/14439262/2309376
TL;DR You cannot use an instance variable as a constructor parameter for another instance variable. If you make the CookieContainer and the HttpClientHandler static members then the error will go away - but that may have implications on your code.
private static CookieContainer cookieContainer = new CookieContainer();
private static HttpClientHandler clienthandler =
new HttpClientHandler {
AllowAutoRedirect = true,
UseCookies = true,
CookieContainer = cookieContainer };
private HttpClient client = new HttpClient(clienthandler);
A better solution might be to put all the initialization code into the constructor of the class
class Test
{
private static CookieContainer cookieContainer;
private static HttpClientHandler clienthandler;
private HttpClient client;
public Test()
{
cookieContainer = new CookieContainer();
clienthandler = new HttpClientHandler { AllowAutoRedirect = true, UseCookies = true, CookieContainer = cookieContainer };
client = new HttpClient(clienthandler);
}
}
Problem
I am logging in to a website and trying to get the session and cookies, my cookie container is outside my methods which works find, but I can not get cookies and send them with my requestions, I tried to use the handler the same way as my cookie container but I get an error a field initializer cannot reference the nonstatic field c# Here's what I was trying to do ``` private CookieContainer cookieContainer = new CookieContainer(); private HttpClientHandler clienthandler = new HttpClientHandler { AllowAutoRedirect = true, UseCookies = true, cookieContainer }; private HttpClient client = new HttpClient(clienthandler); ``` So how can I go about using the handler so I can set the session and send the session? Thank you.