I'm confused how CookieContainer handles domain, so I create this test.
This test shows cookieContainer doesn't return any cookie for "example.com" but according to RFC it should return at least 2 cookies.
Isn't it a bug?
How make it to work?
Here is a discussion about this bug:
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>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…