C# 使用支持Cookie的WebClient

C# 使用支持Cookie的WebClient,c#,cookies,webclient,C#,Cookies,Webclient,我正在使用登录网站: public class CookieAwareWebClient : WebClient { public CookieAwareWebClient() { CookieContainer = new CookieContainer(); } public CookieContainer CookieContainer { get; private set; } pr

我正在使用登录网站:

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。

有什么想法吗?

一切正常,只是我忘了设置饼干,谢谢:


您从未设置cookie,UploadValues不会将值集合应用于cookie。另外,您的“工作程序”正在执行一个
GET
,这将是
DownloadXxxxx
方法之一,而不是上载方法。@ScottChamberlain如何设置cookie?不是100%确定,但我将从以下方法之一开始:methods@ScottChamberlain谢谢。
client.CookieContainer.SetCookies(new Uri("http://example.com//dl27929"), "username=john; password=secret;");