Using httpclient in all methods without losing session and cookies

I enter the site and try to get session and cookies, my cookie container is outside of my methods that find work, but I cannot get the cookies and send them with my requests, I tried to use the handler just like my cookie container but I get the error

field initializer cannot refer to non-static field c #

This is what I tried 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 use a handler to establish a session and send a session? Thank.

+3


source to share


1 answer


Your answer is here: fooobar.com/questions/112473 / ...

TL; DR You cannot use an instance variable as a constructor parameter for another instance variable. If you create the static members CookieContainer and HttpClientHandler, the error goes away, but it could have implications for 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 include all the initialization code in the class constructor

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);
    }
}

      

0


source







All Articles