Cookies and Unicode characters

本文探讨了在ASP.NET中使用Cookies存储Unicode字符时遇到的问题及解决方案。当尝试从Cookies中读取Unicode字符时,它们会变成不可读的形式。解决办法是对Cookie值进行URL编码,无论页面采用何种编码方式都能正常工作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载:http://blog.madskristensen.dk/post/Cookies-and-Unicode-characters.aspx

Cookies and Unicode characters

by Mads Kristensen 9. September 2007

I’ve been having some issues with storing Unicode characters in cookies today. Whenever a cookie is set and the value filled with Unicode characters, the same characters cannot be retrieved from the cookie again. When they are retrieved from the requesting browser, they are changed into something totally unreadable.

Background

The cookie is set when a visitor enters some text into a textbox and submits the form. When the same visitor returns to that page I wanted to pre-fill the textbox with the value submitted earlier. Very easy and simple and not before someone noticed the strange behaviour with Unicode characters I thought it worked just fine.

Because the value was displayed in a textbox I thought that maybe HTML encoding could solve the issue. Don’t ever HTML encode a cookie in ASP.NET! It results in a yellow screen of death and an exception stating that the cookie contains dangerous characters. The dangerous character it was referring to was a HTML encoded representation of a Unicode character and looked something like this "#248;". The only thing to do is to delete your cookies in order to view that page again.

The solution

It took me a while to figure it out, but all you need to do is to URL encode the cookie value. It works no matter what encoding you use for the page. The example below illustrates the very simple solution:

private void SetCookie()
{
  HttpCookie cookie = new HttpCookie("cookiename");
  cookie.Expires = DateTime.Now.AddMonths(24);
  cookie.Values.Add("name", Server.UrlEncode(txtName.Text));
  Response.Cookies.Add(cookie);
}

private void GetCookie()
{
  HttpCookie cookie = Request.Cookies["cookiename"];
  if (cookie != null)
  {
    txtName.Text = Server.UrlDecode(cookie.Values["name"]);
  }
}

It is so simple but caused me a lot of time investigating and clearing cookies from the browser.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值