c#中cookie的使用總結

來源:互聯網
上載者:User
今天在使用cookie是過程中,遇到一些問題:
一個是cookie在讀取內容時總是顯示亂碼:一直不明白為什麼會這樣,後來想來想去,就想到用Server.UrlEncode對內容進行編碼、之後在顯示的時候在解碼:

下面是一個自己寫的簡單的cookie例子
完整代碼如下:
protected void Button2_Click(object sender, EventArgs e)
{
String CookieName = "123";
HttpCookie cookie = new HttpCookie(CookieName);
cookie.Value =Server.UrlEncode ("韓貴州");
DateTime dtNow = DateTime.Now;
TimeSpan tsMinute = new TimeSpan(0, 1, 0, 0);
cookie.Expires = dtNow + tsMinute;
Response.Cookies.Add(cookie );
Label1.Text = cookie.Value;
}
protected void Button1_Click(object sender, EventArgs e)
{
HttpCookie GetCookie = Request.Cookies["123"];
if (null == GetCookie)
{
Response.Write("未找到對應的的cookie");
}
else
{
Label1.Text = Server.UrlDecode(GetCookie.Value.ToString());

}
}

此外,還有一點要說明 的就是:判斷cookie內容是否存在的方法是
If(null==cookie名稱)

第三:就是注意cookie的存活時間:
在本例子中。它的存活時間是一個小時。
DateTime dtNow = DateTime.Now;
TimeSpan tsMinute = new TimeSpan(0, 1, 0, 0);
cookie.Expires = dtNow + tsMinute;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.