Search code examples
c#cookieswebclientcookiejar

WebClient login with Cookie and download String


I login with HTTPWebRequest and transfer the CookieContainer to the new class and want my WebClient to log in with this cookie and download a site as string. But I only get the source code of the login page, so it seems like the webclient won't login.

This is my current code:

        BasicAuthentication login = new BasicAuthentication();
        CookieContainer cookieJar = login.getCookie();

        WebClientEx client = new WebClientEx();
        client.Cookies = cookieJar;

And the WebClientEx Class

    class WebClientEx : WebClient
{
    private CookieContainer _cookies;
    private string _ref;
    public WebClientEx()
    {
        _cookies = new CookieContainer();
    }
    public CookieContainer Cookies
    {
        get { return _cookies; }
        set { _cookies = value; }
    }
    protected override WebRequest GetWebRequest(System.Uri address)
    {
        var webReq = base.GetWebRequest(address);
        if (webReq is HttpWebRequest)
        {
            var req = (HttpWebRequest)webReq;
            req.CookieContainer = _cookies;
            if (_ref != null)
            {
                req.Referer = _ref;
            }
        }
        _ref = address.ToString();
        return webReq;
    }
    protected override void Dispose(bool disposing)
    {
        _cookies = null;
        base.Dispose(disposing);
    }
}

Solution

  • I just get an Answer to my question. Here's a example of my code:

            WebClient client = new WebClient();
            client.Headers.Add(HttpRequestHeader.Cookie, "cookievalue");
            string download = client.DownloadString("url");
            output.Text = download;
    

    In the variable cookievalue I only enter the cookiename=cookievalue. I get the name and the value from Postman, a useful google chrome tool.

    I just have to make sure that i can redirect to any login proteccted page with postman and when this is true, then I can use cookiename and cookievalue to login my webclient and see all pages and download sites with downloadString.