Asp.net 得到Cookie中值

將 Cookie中的值顯示在頁面上,代碼如下:

public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

//讀取Cookie中的值 scott 20080610

if (Request.Cookies.Count > 0)

{

HttpCookieCollection hccCookie = new HttpCookieCollection();

//得到用戶端Cookie

hccCookie = Request.Cookies;

//得到所有Key

string[] sArr = hccCookie.AllKeys;

Response.Write("hccCookie.allKeys 數量"+sArr.Length+"<br>");

HttpCookie hc;

int i = 1;

foreach (string sCookie in Request.Cookies.AllKeys)

{

Response.Write("第" + i + "值: <br>");

hc = hccCookie[sCookie];

Response.Write(ConvertUtf8(sCookie) + "是否含有子key: " + hc.HasKeys + "<br>");

//判斷有沒有子Key。如果有,循環得出值

if (hc.HasKeys)

{

Response.Write("子Key值為: <br>");

foreach (string sVar in hc.Values)

{

string cookieSubKey = ConvertUtf8(sVar);

string cookieSubValue = ConvertUtf8(hc[sVar]);

Response.Write(cookieSubKey + ": " + cookieSubValue + "<br>");

}

}

//沒有子key時,直接得出值

else

{

Response.Write(ConvertUtf8(sCookie) + "的值:" + ConvertUtf8(hc.Value) + "<br>");

}

i++;

}

}

}

/// <summary>

/// 將內容轉成Utf8

/// </summary>

/// <param name="asValue"></param>

/// <returns></returns>

private string ConvertUtf8(string asValue)

{

System.Text.Encoding encValue = System.Text.Encoding.GetEncoding("utf-8");

//HttpUtility:提供用于在处理 Web 请求时编码和解码 URL 的方法。

string sReturn = HttpUtility.UrlDecode(asValue, encValue);

return sReturn;

}

}