5

我正在开发一个使用 WebClient 的应用程序。我有一个扩展基本 WebClient 功能的类:

public class WebClientEx : WebClient
{
    private CookieContainer _cookieContainer = new CookieContainer();

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);
        if (request is HttpWebRequest)
        {
            (request as HttpWebRequest).CookieContainer = _cookieContainer;
            (request as HttpWebRequest).AllowAutoRedirect = true;
            (request as HttpWebRequest).Timeout = 10000;
        }
        return request;
    }
}

我使用 WebClientEx 登录站点并请求一些信息。它适用于 4.0 和 4.5,但它不适用于早期版本,例如 3.5、3.0 等。我添加了一些调试代码,在早期版本中它说 cookie 容器中有 0 个 cookie,而 4.0+ 则说有是两个cookie,应该是。

所以原因可能是 .NET Framework 的早期版本在将 cookie 存储在 cookie 容器中时存在一些问题。如何解决?

4

2 回答 2

5

我已经确认 .NET 3.5 中的行为与 .NET 4.0 不同。使用以下代码进行测试:

Uri sourceUri = new Uri(@"http://www.html-kit.com/tools/cookietester/");
WebClientEx webClientEx = new WebClientEx();
webClientEx.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
webClientEx.UploadString(sourceUri, "cn=MyCookieName&cv=MyCookieValue");
var text = webClientEx.DownloadString(sourceUri);
var doc = new HtmlAgilityPack.HtmlDocument();
doc.Load(new MemoryStream(Encoding.ASCII.GetBytes((text))));
var node = doc.DocumentNode.SelectNodes("//div").Single(n => n.InnerText.StartsWith("\r\nNumber of cookies received:"));
Debug.Assert(int.Parse(node.InnerText.Split(' ')[4]) == 1);

当然,这并不能回答您的问题;但我看不出为什么会有不同的行为,只是说它可能已在 .NET 4.0 中修复,并且该修复尚未放入 .NET 3.5 或更早版本中。

我尝试了类似的事情HttpWebRequest并遇到了同样的问题(适用于 4,但不是之前):

HttpWebRequest webreq = ((HttpWebRequest) (WebRequest.Create(sourceUri)));
CookieContainer cookies = new CookieContainer();

var postdata = Encoding.ASCII.GetBytes("cn=MyCookieName&cv=MyCookieValue");

webreq.CookieContainer = cookies;
webreq.Method = "POST";
webreq.ContentLength = postdata.Length;
webreq.ContentType = "application/x-www-form-urlencoded";

Stream webstream = webreq.GetRequestStream();
webstream.Write(postdata, 0, postdata.Length);
webstream.Close();

using (WebResponse response = webreq.GetResponse())
{
    webstream = response.GetResponseStream();
    using (StreamReader reader = new StreamReader(webstream))
    {
        String responseFromServer = reader.ReadToEnd();
        var doc = new HtmlAgilityPack.HtmlDocument();
        doc.Load(new MemoryStream(Encoding.ASCII.GetBytes((responseFromServer))));
        var node =
            doc.DocumentNode.SelectNodes("//div").Single(n => n.InnerText.StartsWith("\r\nNumber of cookies received:"));
        Debug.Assert(int.Parse(node.InnerText.Split(' ')[4]) == 1);
    }
}

HttpWebRequest因此, (WebClient使用)似乎存在问题。这可能是新的,因为我已经看到人们在 4.0 发布之前使用这样的代码(可能在 3.50 之前,他们说它有效。

如果情况紧急,我建议联系 Microsoft 支持。如果您有 MSDN 许可证,以下链接将详细说明如何使用随附的 MSDN 支持票提出支持请求:http: //msdn.microsoft.com/en-us/subscriptions/bb266240.aspx 如果您没有 MSDN您可以在此处详细联系支持: https: //support.microsoft.com/oas/default.aspx?Gprid=8291&st=1&wfxredirect=1&sd=gn

如果它不那么紧急,那么您可能会在http://connect.microsoft.com/VisualStudio上记录问题,以查看您是否得到解决方法的响应。

于 2012-08-27T18:20:16.057 回答
2

我刚刚创建了一个基本的 IHttpHandler 来测试这个类,它似乎可以工作。

<%@ WebHandler Language="C#" Class="CookieTest" %>

using System;
using System.Net;
using System.Web;

public class CookieTest : IHttpHandler
{
    public class WebClientEx : WebClient
    {
        private CookieContainer _cookieContainer = new CookieContainer();

        protected override WebRequest GetWebRequest(Uri address)
        {
            WebRequest request = base.GetWebRequest(address);
            if (request is HttpWebRequest)
            {
                (request as HttpWebRequest).CookieContainer = _cookieContainer;
                (request as HttpWebRequest).AllowAutoRedirect = true;
                (request as HttpWebRequest).Timeout = 10000;
            }
            return request;
        }
    }

    public void ProcessRequest(HttpContext ctxt)
    {
        ctxt.Response.ContentType = "text/plain";

        String cmd = ctxt.Request["cmd"];
        if (cmd == "set")
        {
            ctxt.Response.Cookies.Add(new HttpCookie("test", "test"));
            ctxt.Response.Write("Cookie Set: test = test");
        }
        else if (cmd == "get")
        {
            ctxt.Response.Write("Cookie Value: test = " + ctxt.Request.Cookies["test"].Value);
        }
        else
        {
            // run out tests
            WebClientEx wc = new WebClientEx();

            ctxt.Response.Write("Running tests on .NET version: " + Environment.Version);
            ctxt.Response.Write(Environment.NewLine + Environment.NewLine);
            ctxt.Response.Write("Setting Cookie...");
            ctxt.Response.Write(Environment.NewLine + Environment.NewLine);
            ctxt.Response.Write("Response: " + wc.DownloadString(ctxt.Request.Url.AbsoluteUri + "?cmd=set"));
            ctxt.Response.Write(Environment.NewLine + Environment.NewLine);
            ctxt.Response.Write("Getting Cookie...");
            ctxt.Response.Write(Environment.NewLine + Environment.NewLine);
            ctxt.Response.Write("Response: " + wc.DownloadString(ctxt.Request.Url.AbsoluteUri + "?cmd=get"));
            ctxt.Response.Write(Environment.NewLine + Environment.NewLine);
        }
    }

    public bool IsReusable
    {
        get { return true; }
    }
}

我得到的结果是:

在 .NET 版本上运行测试:2.0.50727.5456

正在设置 Cookie...

响应:Cookie 集:测试 = 测试

获取饼干...

响应:Cookie 值:test = test

这对你来说是否正确?

于 2012-08-21T22:09:22.873 回答