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

后端 未结 2 1421
南旧
南旧 2020-12-15 22:46

I\'m creating a client to visit a website and log in + do some tasks automatically, however they recently updated their cookies to (for whatever reason...) contain a comma i

相关标签:
2条回答
  • 2020-12-15 23:11

    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.

    0 讨论(0)
  • 2020-12-15 23:13

    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"]);
    
    0 讨论(0)
提交回复
热议问题