c# – Cookie returning duplicate value


I'm saving an object in JSON format in a cookie. In the properties of this object I have links with several parameters. With every link change, I update the cookie with the new value. Example of the value saved in the cookie:

{"Url":"https://www.site.com.br? utm_source=parceiro&utm_medium=Banner&utm_campaign=campanha","Valor":"https://www.site.com.br"} 

When accessing the page for the first time, the value saved in the cookie is correct. However, when refreshing the page, the value appears as follows:


Parameters appear repeated. With each update the number of parameters increases. I added logs and verified that the value in the cookies is correct, it only appears with several equal parameters when I return the saved value of the cookies. I tested using XML instead of JSON and the same thing happened. Example of creating cookies:

    public static void SalvarCookie(string nome, string valor, int dias)
        HttpCookie cookie = HttpContext.Current.Request.Cookies[nome];

        if (cookie != null)
            cookie.Expires = DateTime.Now.AddDays(-1);

        cookie = new HttpCookie(nome, valor);

        cookie.Expires = DateTime.Now.AddDays(dias);
        cookie.HttpOnly = true;
        cookie.Secure = true;

Code to convert object to JSON:

    public static string ConvertToJson(object valor)
        return Newtonsoft.Json.JsonConvert.SerializeObject(valor);

I've tested it with other ways to update the cookie, but they all return the wrong value. In Chrome inspector the cookie value appears correctly, the issue only appears in the code.


Problem solved. The cookie does not work correctly with the & character present in the URL. It worked when I replaced it with %26 .

Scroll to Top