Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using httpclient throughout methods without losing session and cookies

Tags:

c#

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.

like image 875
Oracrin Gaming Avatar asked May 10 '17 05:05

Oracrin Gaming


People also ask

Why do we need HttpClient in C#?

The HttpClient class instance acts as a session to send HTTP requests. An HttpClient instance is a collection of settings applied to all requests executed by that instance. In addition, every HttpClient instance uses its own connection pool, isolating its requests from requests executed by other HttpClient instances.


1 Answers

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);
    }
}
like image 179
Simply Ged Avatar answered Sep 20 '22 13:09

Simply Ged