handling a comma inside a cookie value using .net's (C#) System.Net.Cookie

只愿长相守 提交于 2019-11-29 01:32:20
Seb Nilsson

According to the following article, you should consider UrlEncode and UrlDecode for storing values in cookies.

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"]);
    }
}

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.

MSDN also has an article on the subject.

ASP.NET does not encode or unencode cookies in UrlEncode format by default. As a result, you may encounter unexpected behavior in ASP.NET applications.

To handle the cookie, since a cookie is essentially a string, you may like to try URL Encoding the cookie value before setting it, and then Decoding it when you pull out the value.

i.e.:

Response.Cookies["Value1"] = Server.UrlEncode(sCookieValue);

and similarly:

string sCookieValue = Server.UrlDecode(Request.Cookies["Value1"]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!