4

I'm using this enhanced version of WebClient to login in a site:

public class CookieAwareWebClient : WebClient
{
        public CookieAwareWebClient()
        {
            CookieContainer = new CookieContainer();
        }
        public CookieContainer CookieContainer { get; private set; }

        protected override WebRequest GetWebRequest(Uri address)
        {
            var request = (HttpWebRequest)base.GetWebRequest(address);
            request.CookieContainer = CookieContainer;
            return request;
        }
}

And this way I send cookie to the site:

using (var client = new CookieAwareWebClient())
{
    var values = new NameValueCollection
    {
        { "username", "john" },
        { "password", "secret" },
    };
    client.UploadValues("http://example.com//dl27929", values);

    // If the previous call succeeded we now have a valid authentication cookie
    // so we could download the protected page
    string result = client.DownloadString("http://domain.loc/testpage.aspx");
}

But when I run my program and capture the traffic in Fiddler I get 302 status code. I tested the request in Fiddler this way and everything is OK and I get the status code of 200.
The request in the Fiddler:

GET http://example.com//dl27929 HTTP/1.1
Cookie: username=john; password=secret;
Host: domain.loc

And here is the request sending by the application:

POST http://example.com//dl27929 HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: www.domain.loc
Content-Length: 75
Expect: 100-continue
Connection: Keep-Alive

As you can see it doesn't send the cookie.
Any idea?

3
  • 2
    You never set the cookie, UploadValues does not apply the value collection to the cookies. Also your "working program" is doing a GET which would be one of the DownloadXxxxx methods not a Upload method. Commented Jun 30, 2015 at 4:56
  • @ScottChamberlain How can I set the cookie? Commented Jun 30, 2015 at 4:57
  • Not 100% sure but I would start with one of the client.CookieContainer.Add( methods Commented Jun 30, 2015 at 4:58

1 Answer 1

2

Everything works fine, just I forgot to set the cookie, Thanks Scott:

client.CookieContainer.SetCookies(new Uri("http://example.com//dl27929"), "username=john; password=secret;");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.