Using Cookie aware WebClient
10,992
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;");
Comments
-
Sirwan Afifi almost 2 years
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?