Cookie怎麼寫就怎麼讀
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class B : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//產生一個Cookie
HttpCookie cookie = new HttpCookie("test");
//設定單值
cookie.Value = Server.UrlEncode("Hello!!世界");
//設定過期日
cookie.Expires = DateTime.Now.AddDays(2);
//寫到用戶端
Response.Cookies.Add(cookie);
}
}
//讀取cookie(以多值的方式)
protected void btn_test_Click(object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies["test"];
foreach (string value in cookie.Values)
{
Response.Write("Null?"+(value==null)+"<br/>");/*順便測試看看是否為null還是空字串*/
Response.Write("空字串?"+(value=="")+"<br/>");
Response.Write("foreach迴圈中撈出Request.Cookies['test']所有的Value:" + Server.UrlDecode(value)+"<hr/>");
}
Response.Write("Null?"+(cookie["test"]==null)+"<br/>");
Response.Write("空字串?" + (cookie["test"]=="")+"<br/>");
Response.Write("cookie['test'](HttpCookie物件裡索引名為test的值):"+Server.UrlDecode(cookie["test"])+"<hr/>");
}
}
沒有留言:
張貼留言