當我們需要發送多值Cookie的時候,可以使用下面的方法設置多值 Cookie.
C# 代碼
System.Net.HttpWebRequest r = System.Net.HttpWebRequest.Create("http://www.mengxianhui.com:8081/b.aspx") as System.Net.HttpWebRequest;
r.Headers["Cookie"] = "Url=http://dotnet.aspx.cc; UserInfo=UserName=" + System.Web.HttpUtility.UrlEncode("孟憲會") + "&UserId=net_lover";
r.Proxy = null;
System.Net.HttpWebResponse response = r.GetResponse() as System.Net.HttpWebResponse;
this.textBox1.Text = new System.IO.StreamReader(response.GetResponseStream()).ReadToEnd();
response.Close();
或者這樣
C# 代碼
System.Net.CookieCollection ccl = new System.Net.CookieCollection();
System.Net.CookieContainer cc = new CookieContainer();
System.Net.Cookie c = new Cookie("UserInfo","UserName=" + System.Web.HttpUtility.UrlEncode("孟憲會") + "&UserId=net_lover");
c.Domain = "mengxianhui.com";
ccl.Add(c);
c = new Cookie("Url","http://dotnet.aspx.cc");
c.Domain = "mengxianhui.com";
ccl.Add(c);
cc.Add(ccl);
System.Net.HttpWebRequest r = System.Net.HttpWebRequest.Create("http://www.mengxianhui.com:8081/b.aspx") as System.Net.HttpWebRequest;
r.CookieContainer = cc;
r.Proxy = null;
System.Net.HttpWebResponse response = r.GetResponse() as System.Net.HttpWebResponse;
this.textBox1.Text = new System.IO.StreamReader(response.GetResponseStream()).ReadToEnd();
response.Close();
接收端:
ASPX 代碼
<%@ Page Language="C#" AutoEventWireup="true" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Cookies["UserInfo"] != null)
{
Response.Write("你設置的分別是Cookie:" + System.Environment.NewLine + System.Environment.NewLine);
HttpCookie aCookie = Request.Cookies["UserInfo"];
Response.Write("UserName = " + System.Web.HttpUtility.UrlDecode(aCookie["UserName"]));
Response.Write(System.Environment.NewLine);
Response.Write("UserId = " + aCookie["UserId"]);
Response.Write(System.Environment.NewLine);
Response.Write("Url = " + Request.Cookies["Url"].Value);
}
else
{
Response.Write("你沒有設置Cookie");
}
}
</script>