c#中cookie的乱码[转]
今天在使用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());
}
}
{
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;
TimeSpan tsMinute = new TimeSpan(0, 1, 0, 0);
cookie.Expires = dtNow + tsMinute;
满招损,谦受益,学,永无止境