0

I am using WebClient to try and access a web page. I have to login first and the site sets cookies. I am using code from this question The cookies are being set correctly, however when I try to access the second page I am just returned to the login page.

private WebClientEx client;
public string GetFile(string URL)
    {
        Login();
        // Download desired page
        return client.DownloadString(URL);
    }

    private void Login()
    {
        using (client)
        {
            var values = new NameValueCollection
            {
                { "Login", "xxxx" },
                { "Password", "xxxx" },
            };
            // Authenticate
            client.UploadValues("http://www.xxxxxx.com/backoffice/login.php");
        }
        return;
    }
}


/// <summary>
/// A custom WebClient featuring a cookie container
/// </summary>
public class WebClientEx : WebClient
{
    public CookieContainer CookieContainer { get; private set; }

    public WebClientEx()
    {
        CookieContainer = new CookieContainer();
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);

        if (request.GetType() == typeof(HttpWebRequest))
            ((HttpWebRequest)request).CookieContainer = CookieContainer;

        return request;
    }
}
Community
  • 1
  • 1
Fred B
  • 126
  • 1
  • 6
  • 1
    Do you keep an instance of WebClientEx alive or do you new for every call? Keeping one instance is crucial... – rene Oct 14 '13 at 18:53
  • I've recently come across needing to use cookies as well. I started with this code: http://blogs.msdn.com/b/omarv/archive/2012/11/15/developing-windows-store-apps-for-sharepoint-online-with-sso-single-sign-on.aspx, which uses HttpClient and ended up using a modified version of HttpWebRequest but as rene mentioned - you need to make sure that you're only using one instance of the client to ensure the cookies persist across requests. – Travis Sharp Oct 14 '13 at 19:19
  • Yes I am keeping an instance of WebClientEX. I must of missed that line when I copied the code. – Fred B Oct 14 '13 at 19:22

0 Answers0