How to retrieve content from a cookie

Asked

Viewed 1,248 times

0

As I do to retrieve the content of a cookie, this cookie has the ID of the material that will be requested and the amount, I need to recover to enter in the bank. I’ve searched the Internet a lot, and I haven’t figured out how to do that yet. Follow the code of how I create the cookie and enter the values in it.

    [Authorize]
    public void AddCarrinho(String Qtd, String Id)
    {
        HttpCookie cookie;
        if(Request.Cookies["pedido"] == null)
        {
            cookie = new HttpCookie("pedido");
        }
        else
        {
            cookie = (HttpCookie)Request.Cookies["pedido"];
        }
        cookie.Expires = DateTime.Now.AddHours(1); //cookie expira depois de 1 hora
        cookie.Values.Add(Id, Qtd);
        Response.Cookies.Add(cookie);
    }

Edited

Follow the code of how I did after Gypsy Morison’s reply and it didn’t work.

    public void AddCarrinho(String Id, String Qtd)
    {
        HttpCookie cookie;
        if (Request.Cookies["teste"] == null)
        {
            cookie = new HttpCookie("teste");
        }
        else
        {
            cookie = (HttpCookie)Request.Cookies["teste"];
        }
        cookie.Expires = DateTime.Now.AddHours(1); //cookie expira depois de 1 hora
        cookie.Values.Add(Id, Qtd);
        Response.Cookies.Add(cookie);
    }

    public ActionResult Recuperar()
    {
        Teste t = new Teste();

        List<Teste> lst = new List<Teste>();

        if(Request.Cookies["teste"]["Id"] != null && Request.Cookies["teste"]["Qtd"] != null)
        {
            for(int i = 0; i < Request.Cookies.Count; i++)
            {
                t.ID = Request.Cookies["teste"]["Id"];
                t.Quantidade = Request.Cookies["teste"]["Qtd"];
                lst.Add(t);
            }
        }

        return View(lst);
    }

Edited

Debug

1 answer

2

A cookie is a dictionary, so:

if (Request.Cookies["pedido"][Id] != null) 
{ 
    minhaInformacao = Request.Cookies["pedido"][Id]; 
}
  • Gypsy, I edited the question and posted the code of how I did, did not work, see if there is something wrong please. Thank you.

  • @Alanalmeida At the moment you perform Recuperar, when you inspect Request.Cookies, what’s inside of her?

  • You want me to run a screen print for you to see?

  • @Alanalmeida may be. I need to know what’s inside the variable.

  • This added, I edited the question.

  • @Alanalmeida AllKeys says nothing. You need to expand the enumerable through the property Result to see what you have filled.

  • you refer to the last option that has the name of Result View? if it is, it has the same result [0] "test"

Show 2 more comments

Browser other questions tagged

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