我很困惑 CookieContainer 如何处理域,所以我创建了这个测试。这个测试表明 cookieContainer 没有为“example.com”返回任何 cookie,但根据 RFC,它应该返回至少 2 个 cookie。
这不是一个错误吗?
如何让它发挥作用?
以下是关于此错误的讨论:
http://social.msdn.microsoft.com/Forums/en-US/ncl/thread/c4edc965-2dc2-4724-8f08-68815cf1dce6
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Net" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
CookieContainer getContainer()
{
CookieContainer result = new CookieContainer();
Uri uri = new Uri("http://sub.example.com");
string cookieH = @"Test1=val; domain=sub.example.com; path=/";
result.SetCookies(uri, cookieH);
cookieH = @"Test2=val; domain=.example.com; path=/";
result.SetCookies(uri, cookieH);
cookieH = @"Test3=val; domain=example.com; path=/";
result.SetCookies(uri, cookieH);
return result;
}
void Test()
{
CookieContainer cookie = getContainer();
lblResult.Text += "<br>Total cookies count: " + cookie.Count + " expected: 3";
Uri uri = new Uri("http://sub.example.com");
CookieCollection coll = cookie.GetCookies(uri);
lblResult.Text += "<br>For " + uri + " Cookie count: " + coll.Count + " expected: 2";
uri = new Uri("http://other.example.com");
coll = cookie.GetCookies(uri);
lblResult.Text += "<br>For " + uri + " Cookie count: " + coll.Count + " expected: 2";
uri = new Uri("http://example.com");
coll = cookie.GetCookies(uri);
lblResult.Text += "<br>For " + uri + " Cookie count: " + coll.Count + " expected: 2";
}
protected void Page_Load(object sender, EventArgs e)
{
Test();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>CookieContainer Test Page</title>
</head>
<body>
<form id="frmTest" runat="server">
<asp:Label ID="lblResult" EnableViewState="false" runat="server"></asp:Label>
</form>
</body>
</html>