【问题标题】:Using Cookie aware WebClient使用 Cookie 感知 WebClient
【发布时间】:2015-09-16 17:40:56
【问题描述】:

我正在使用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,UploadValues 不会将值集合应用于 cookie。此外,您的“工作程序”正在执行 GET,这将是 DownloadXxxxx 方法之一,而不是 Upload 方法。
  • @ScottChamberlain 如何设置 cookie?
  • 不是 100% 肯定,但我会从 client.CookieContainer.Add( 方法之一开始
  • @ScottChamberlain 非常感谢。

标签: c# cookies webclient


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-14
    • 2019-06-21
    • 2014-06-04
    • 2023-03-03
    • 2014-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多