Response.cookies和Request.cookies

394778101發表於2016-06-30

Response.cookies和Request.cookies的區別很重要,由於方法基本都是差不多的,特別對於初學者而言,很容易出現混淆。
簡單說就是建立cookie用response,獲取cookie值用request。

下面是建立cookie的程式碼,轉自微軟MSDN

方法一:
Response.Cookies["userName"].Value = "patrick";
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1);
方法二:使用HttpCookie類
HttpCookie aCookie = new HttpCookie("lastVisit");
aCookie.Value = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);

以下是讀取cookie值的程式碼

if(Request.Cookies["userName"] != null)
    Label1.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);

if(Request.Cookies["userName"] != null)
{
    HttpCookie aCookie = Request.Cookies["userName"];
    Label1.Text = Server.HtmlEncode(aCookie.Value);
}

相關文章