Cookie returning duplicate value

Asked

Viewed 71 times

3

I am cookie saving an object in JSON format. In the properties of this object I have links with several parameters. With each 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 updating the page the value appears as follows:

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

The parameters appear repeated. Each update increases the number of parameters. I added logs and verified that the value in cookies is correct, it only appears with several equal parameters at the moment that return the saved value of cookies. I tested using XML instead of JSON and the same thing happened. Example of cookie creation:

    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;
        HttpContext.Current.Response.Cookies.Add(cookie);
    }

Code to convert the object to JSON:

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

I did the test with other ways to update the cookie, but they all return the wrong value. In the Chrome inspector the cookie value appears correctly, the problem appears only in the code.

1 answer

1

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.