使用Cookie感知WebClient

时间:2015-06-30 04:29:13

标签: c# cookies webclient

我使用this enhanced version of WebClient登录网站:

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;
        }
}

这样我就会向网站发送cookie:

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");
}

但是当我运行程序并捕获Fiddler中的流量时,我得到302状态代码。我用这种方式在Fiddler中测试了请求,一切正常,我得到200的状态代码 小提琴手中的请求:

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

这是应用程序发送的请求:

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

你可以看到它没有发送cookie 有什么想法吗?

1 个答案:

答案 0 :(得分:1)

一切正常,我忘了设置cookie,谢谢Scott

client.CookieContainer.SetCookies(new Uri("http://example.com//dl27929"), "username=john; password=secret;");