简体   繁体   中英

How to set Swedish letters to their original state after a cookie request

I have a code in my base page that retrieves a user name ( IDname ) from an SQL database then saves the name in a cookie as follows:

HttpCookie ckIDname = new HttpCookie("ckIDname");
ckIDname.Value = IDname;
Response.Cookies.Add(ckIDname);

The cookie is retrieved as follows:

public static HttpCookie ckIDname { get { return HttpContext.Current.Request.Cookies["ckIDname"]; } }
public static string ckIDnameValue { get { if (ckIDname != null) return ckIDname.Value as string; else return string.Empty; } }

So far so good. However if the cookie contains Swedish letters (åäö) I only get encoded characters (ie if IDname is Göran I get it from the cookie as G%C3%83%C2%B6ran).

I tried many attempts ( HttpUtility.HtmlEncode , HttpUtility.HtmlDecode , HttpUtility.UrlDecode ) to get the letters to their original state but without luck. The name in the SQL database is correct (Göran). Moreover I don't have any problem writing Swedish letters in HTML tags. They are all correct. My only problem is to get Swedish letters from cookies correctly. Any help would be highly appreciated!

Try UrlEncode the value before you set it in the cookie.

ckIDname.Value = HttpUtility.UrlEncode(IDname);

Then UrlDecode after you retrieved it.

You cannot reliably store non-ASCII characters in cookies. You've found that there is an attempt to meaningfully convert non-ASCII characters to an ASCII encoding, but how and when this happens is generally unreliable .

For best results, do it yourself. Pick an encoding function that produces results that are valid in cookies, and the question of which decoding function you need should become obvious. For instance, if you use HttpUtility.HtmlEncode for encoding, use HttpUtility.HtmlDecode for decoding. However, while it might work, HttpUtility.HtmlEncode wouldn't really be a sensible encoding here.

You already found HttpUtility.UrlDecode . That, along with HttpUtility.UrlEncode for encoding, seems like a good one to me, since the restrictions on valid characters in URLs are pretty similar to the restrictions on valid characters in cookies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM