使用 Cookie 感知 WebClient

Using Cookie aware 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的状态码。
Fiddler中的请求:

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。
有什么想法吗?

一切正常,只是我忘记设置 cookie,谢谢 Scott:

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