2、C#如何读取Cookie
读取指定的Cookie比起写入Cookie要容易的多,只需要使用" Request.Cookies" 对象就可以完成。
读取指定Cookie名称的方法:
HttpCookie cookie = Request.Cookies [ " Cookie的名称" ] ;
显示已经读取了的Cookie的数值:
Response.Write (cookie . Value . ToString ( ) ) ;
掌握以上要点,读取Cookie就显得非常容易了,下列是读取Cookie的程序代码(read.aspx):
复制代码 代码如下:
<% @ language = "C#" %>
<script runat = "server" >
void ReadClicked ( Object Sender , EventArgs e )
{
//得到用户输入的cookie名称
String strCookieName = NameField . Text ;
//获得cookie
HttpCookie cookie = Request.Cookies [ strCookieName ] ;
//确定是否存在用户输入的cookie
if ( null == cookie ) {
Response.Write ( "没有发现指定的cookie <br > <hr > " ) ;
}
else {
//找到指定的cookie,显示cookie的值
String strCookieValue = cookie . Value . ToString ( ) ;
Response.Write ( strCookieName + " cookie 的值为: <b > "
+ strCookieValue + " </b > <br > <hr > " ) ;
}
}
</script >
<html >
<body >
在 C#页面中读取指定Cookie值<br >
<form runat = "server" >
请输入要读取的Cookie名称:<asp:textbox id = "NameField" runat = "server" />
<asp:button text = "读取cookie" onclick = "ReadClicked" runat = "server" />
</form >
</body >
</html >