使用浏览器cookie

1.创建Cookie

<script runat="server">
protected void btnAdd_Click(object sender, EventArgs e)
{
Response.Cookies["message"].Value = txtCookieValue.Text;//对文本框输入的内容创建Cookie
}

</script>

<form id="form1" runat="server">
<div >
<asp:Label ID="lblCookieValue" Text="Cookie Value:" AssociatedControlID="txtCookieValue" runat="server"/>
<asp:TextBox ID="txtCookieValue" runat="server" />
<asp:Button ID="btnAdd" Text="Add Value" OnClick="btnAdd_Click" runat="server" />

</div>
</form>

2.创建持久化Cookie

<script runat="server">
void Page_Load()
{
//Get current value of cookie
int counter = 0;
if (Request.Cookies["counter"] != null)
{
counter = Int32.Parse(Request.Cookies["counter"].Value);
//Increment counter
counter++;
//Add persistent cookie to browser
Response.Cookies["counter"].Value = counter.ToString();
Response.Cookies["counter"].Expires = DateTime.Now.AddYears(2);
//Display value of counter cookie
lblCounter.Text = counter.ToString();
}
}

</script>

 3.Cookie的属性

HttpCookie类代表cookie。当创建或读取一个cookie时,可以使用以下属性

(1)Domain—用于指定关联到cookie的域名,默认值是当前域名;

(2)Expires—用于通过指定一个过期时间创建一个持久化cookie;

(3)HasKeys—用于确定该cookie是否是一个多值的cookie;

(4)HttpOnly—用于避免cookie被Javascript访问;

(5)Name—用户指定cookie的名称;

(6)Path—用于指定关联到cookie的路径。默认为/。

(7)Secure—用于指定cookie需要通过SSL连接传递;

(8)Value—允许读/写cookie的值;

(9)Values—当使用多值cookie时,用于读/写特定的值;

posted on 2016-05-25 16:09  Floatbarrier  阅读(168)  评论(0编辑  收藏  举报

导航