2

I'm facing an issue using HttpCookie.
I'm building an Ecommerce and I'm trying to set Cookies for my Website.
There are three Cookies defined as describe bellow:

private static string cookienameCampanha = "WLC-Ecommerce-Campanha";
private static string cookienameUsuario = "WLC-Ecommerce-Usuario";
private static string cookienameRodape = "WLC-Ecommerce-Rodape";

All of then is used when HttpCookie is instantiated as bellow:

HttpCookie cookiehelper = new HttpCookie(cookienameCampanha);
HttpCookie cookiehelper = new HttpCookie(cookienameUsuario);
HttpCookie cookiehelper = new HttpCookie(cookienameRodape);

When user access index page for my Ecommerce, all those Cookies were setted. And they have specific definitions.

The third one, cookienameRodape, is used for setting content in footer and my web site shows those contents.
But after index page got fully reload and my footer listed all content, My Web Browser shows that all cookienameRodape content was erased and when I redirect the page to any other pages inside my site, all content is empty.

Something is weird, in DevTools using Chrome I can see other two Cookies Content setted and not erased, but "WLC-Ecommerce-Rodape" is not there even all content is listed in index page.

See the print below:

Cookie Setted

We can check My Index page and all content in my footer:

Footer com Conteudo

But when I try to navegate through my webSite, suddenly all content desapeared:

Footer sem Conteudo

Additionaly, When always returned to index page, all Cookies are setted again and then all content inside footer are listed.
I tryed to search all over the SO and none of then suited me.

All Cookies are removed when user logged out. There is no any moment this happend.

After All content came from DataBase, Footer Contents were defined as below:

public static class AuxiliarCookieBLL
{
    public static List<CampanhaInstitucionalModel> GetCampanhaInstitucional()
    {
        CookieHelper cookiehelper = new CookieHelper(cookienameRodape);

        if (!String.IsNullOrEmpty(cookiehelper.GetFromCookie("CampanhaInstitucional")))
        {
            List<CampanhaInstitucionalModel> CampanhaInstitucional = JsonConvert.DeserializeObject<List<CampanhaInstitucionalModel>>(HttpUtility.UrlDecode(cookiehelper.GetFromCookie("CampanhaInstitucional")));
            return CampanhaInstitucional;
        }
        else
            return new List<CampanhaInstitucionalModel>();

    }

    public static void SetCampanhaInstitucional(List<CampanhaInstitucionalModel> CampanhaInstitucional)
    {
        CookieHelper cookiehelper = new CookieHelper(cookienameRodape);
        if (CampanhaInstitucional != null)
        {
            string campanha = JsonConvert.SerializeObject(CampanhaInstitucional);
            cookiehelper.AddToCookie("CampanhaInstitucional", HttpUtility.UrlEncode(campanha));
        }
    }

    public static List<CampanhaAtendimentoModel> GetCampanhaAtendimento()
    {
        CookieHelper cookiehelper = new CookieHelper(cookienameRodape);

        if (!String.IsNullOrEmpty(cookiehelper.GetFromCookie("CampanhaAtendimento")))
        {
            List<CampanhaAtendimentoModel> CampanhaAtendimento = JsonConvert.DeserializeObject<List<CampanhaAtendimentoModel>>(HttpUtility.UrlDecode(cookiehelper.GetFromCookie("CampanhaAtendimento")));
            return CampanhaAtendimento;
        }
        else
            return new List<CampanhaAtendimentoModel>();

    }

    public static void SetCampanhaAtendimento(List<CampanhaAtendimentoModel> CampanhaAtendimento)
    {
        CookieHelper cookiehelper = new CookieHelper(cookienameRodape);
        if (CampanhaAtendimento != null)
        {
            string campanha = JsonConvert.SerializeObject(CampanhaAtendimento);
            cookiehelper.AddToCookie("CampanhaAtendimento", HttpUtility.UrlEncode(campanha));
        }
    }

    public static List<CampanhaCentralAtendimentoModel> GetCampanhaCentralAtendimento()
    {
        CookieHelper cookiehelper = new CookieHelper(cookienameRodape);

        if (!String.IsNullOrEmpty(cookiehelper.GetFromCookie("CampanhaCentralAtendimento")))
        {
            List<CampanhaCentralAtendimentoModel> CampanhaCentralAtendimento = JsonConvert.DeserializeObject<List<CampanhaCentralAtendimentoModel>>(HttpUtility.UrlDecode(cookiehelper.GetFromCookie("CampanhaCentralAtendimento")));
            return CampanhaCentralAtendimento;
        }
        else
            return new List<CampanhaCentralAtendimentoModel>();

    }

    public static void SetCampanhaCentralAtendimento(List<CampanhaCentralAtendimentoModel> CampanhaCentralAtendimento)
    {
        CookieHelper cookiehelper = new CookieHelper(cookienameRodape);
        if (CampanhaCentralAtendimento != null)
        {
            string campanha = JsonConvert.SerializeObject(CampanhaCentralAtendimento);
            cookiehelper.AddToCookie("CampanhaCentralAtendimento", HttpUtility.UrlEncode(campanha));
        }
    }

    public static List<CampanhaCertificadoModel> GetCampanhaCertificado()
    {
        CookieHelper cookiehelper = new CookieHelper(cookienameRodape);

        if (!String.IsNullOrEmpty(cookiehelper.GetFromCookie("CampanhaCertificado")))
        {
            List<CampanhaCertificadoModel> CampanhaCertificado = JsonConvert.DeserializeObject<List<CampanhaCertificadoModel>>(HttpUtility.UrlDecode(cookiehelper.GetFromCookie("CampanhaCertificado")));
            return CampanhaCertificado;
        }
        else
            return new List<CampanhaCertificadoModel>();

    }

    public static void SetCampanhaCertificado(List<CampanhaCertificadoModel> CampanhaCertificado)
    {
        CookieHelper cookiehelper = new CookieHelper(cookienameRodape);
        if (CampanhaCertificado != null)
        {
            string campanha = JsonConvert.SerializeObject(CampanhaCertificado);
            cookiehelper.AddToCookie("CampanhaCertificado", HttpUtility.UrlEncode(campanha));
        }
    }

    public static List<CampanhaFormaPagamentoModel> GetCampanhaFormaPagamento()
    {
        CookieHelper cookiehelper = new CookieHelper(cookienameRodape);

        if (!String.IsNullOrEmpty(cookiehelper.GetFromCookie("CampanhaFormaPagamento")))
        {
            List<CampanhaFormaPagamentoModel> CampanhaFormaPagamento = JsonConvert.DeserializeObject<List<CampanhaFormaPagamentoModel>>(HttpUtility.UrlDecode(cookiehelper.GetFromCookie("CampanhaFormaPagamento")));
            return CampanhaFormaPagamento;
        }
        else
            return new List<CampanhaFormaPagamentoModel>();

    }

    public static void SetCampanhaFormaPagamento(List<CampanhaFormaPagamentoModel> CampanhaFormaPagamento)
    {
        CookieHelper cookiehelper = new CookieHelper(cookienameRodape);
        if (CampanhaFormaPagamento != null)
        {
            string campanha = JsonConvert.SerializeObject(CampanhaFormaPagamento);
            cookiehelper.AddToCookie("CampanhaFormaPagamento", HttpUtility.UrlEncode(campanha));
        }
    }
}

And now I can show my script footer page when I call all content and list then:

<div class="limite-layout">
    <nav>
        <ul class="col-xs-12 no-padding" id="navFooter">
            <li class="col-md-2 institucional">
                <div>

                    @{
                        rodape.Rodape.ListInstitucional = BLL.AuxiliarCookieBLL.GetCampanhaInstitucional();

                        if (rodape.Rodape.ListInstitucional.Count > 0)
                        {

                            <h6><a href="javascript:void(0)" class="collapsed" data-parent="#navFooter" data-toggle="collapse" data-target="#Institucional"><i class="icon icon-right visible-xs-inline-block visible-sm-inline-block"></i>Institucional</a></h6>
                            <ul id="Institucional" class="collapse">

                                @foreach (var item in rodape.Rodape.ListInstitucional)
                                {
                                    @*<li><a href="@Url.Action("Institucional", "Home", new {id = item.CampanhaRodapeInstitucionalId })" title="@item.Nome">@item.Nome</a></li>*@
                                    <li><a href="@(item.URL + "/" + item.Nome.Replace(" ", "-").ToLower() + "/" + item.CampanhaRodapeInstitucionalId)" title="@item.Nome">@item.Nome</a></li>
                                }
                            </ul>
                        }
                    }

                </div>
            </li>
            <li class="col-md-2 atendimento">
                <div>
                    @{
                        rodape.Rodape.ListAtendimento = BLL.AuxiliarCookieBLL.GetCampanhaAtendimento();

                        if (rodape.Rodape.ListAtendimento.Count > 0)
                        {
                            <h6><a href="javascript:void(0)" class="collapsed" data-parent="#navFooter" data-toggle="collapse" data-target="#Atendimento"><i class="icon icon-right visible-xs-inline-block visible-sm-inline-block"></i>Atendimento</a></h6>
                            <ul id="Atendimento" class="collapse">

                                @foreach (var item2 in rodape.Rodape.ListAtendimento)
                                {
                                    <li><a href="/Home/Atendimento/@(item2.Nome.Replace(" ", "-").ToLower() + "/" + item2.CampanhaRodapeAtendimentoId)" title="@item2.Nome">@item2.Nome</a></li>
                                }

                            </ul>
                        }
                    }
                </div>
            </li>
            <li class="col-md-2 central-atendimento">
                <div>
                    @{
                        rodape.Rodape.ListCentralAtendimento = BLL.AuxiliarCookieBLL.GetCampanhaCentralAtendimento();

                        if (rodape.Rodape.ListCentralAtendimento.Count > 0)
                        {
                            <h6><a href="javascript:void(0)" class="collapsed" data-parent="#navFooter" data-toggle="collapse" data-target="#CentralAtendimento"><i class="icon icon-right visible-xs-inline-block visible-sm-inline-block"></i>Central de Atendimento</a></h6>
                            <ul id="CentralAtendimento" class="collapse">
                                @foreach (var item3 in rodape.Rodape.ListCentralAtendimento)
                                {
                                    <li><a href="/Home/FaleConosco" title="@item3.Nome">@item3.Nome</a></li>
                                }
                            </ul>
                        }
                    }
                </div>
            </li>
            <li class="col-md-3">
                <div class="certificados">
                    @{
                        rodape.Rodape.ListCertificado = BLL.AuxiliarCookieBLL.GetCampanhaCertificado();

                        if (rodape.Rodape.ListCertificado.Count > 0)
                        {
                            <h6><a href="javascript:void(0)" class="collapsed" data-parent="#navFooter" data-toggle="collapse" data-target="#Certificados"><i class="icon icon-right visible-xs-inline-block visible-sm-inline-block"></i>Certificados</a></h6>
                            <ul id="Certificados" class="collapse list-horizontal">
                                @foreach (var item5 in rodape.Rodape.ListCertificado)
                                {
                                    @*<li><a href="@(!String.IsNullOrEmpty(item5.URL) ? item5.URL : "#")"><img alt="@item5.Nome" src="@item5.Descricao" /></a></li>*@
                                    <li><a href="@(!String.IsNullOrEmpty(item5.URL) ? item5.URL : "#")"><img alt="@item5.Nome" src="~/Content/img/conteudo/certificados/ligodaddy.png" /></a></li>
                                    <li><a href="@(!String.IsNullOrEmpty(item5.URL) ? item5.URL : "#")"><img alt="@item5.Nome" src="~/Content/img/conteudo/certificados/clearsale_logo.jpg" /></a></li>
                                    <li><a href="@(!String.IsNullOrEmpty(item5.URL) ? item5.URL : "#")"><img alt="@item5.Nome" src="~/Content/img/conteudo/certificados/ABComm.png" /></a></li>
                                }
                            </ul>
                        }
                    }
                </div>
                <div class="pagamentos">
                    @{
                        rodape.Rodape.ListFormaPagamento = BLL.AuxiliarCookieBLL.GetCampanhaFormaPagamento();

                        if (rodape.Rodape.ListFormaPagamento.Count > 0)
                        {
                            <h6><a href="javascript:void(0)" class="collapsed" data-parent="#navFooter" data-toggle="collapse" data-target="#FormaPagamento"><i class="icon icon-right visible-xs-inline-block visible-sm-inline-block"></i>Formas de Pagamento</a></h6>
                            <ul id="FormaPagamento" class="collapse">
                                @foreach (var item4 in rodape.Rodape.ListFormaPagamento)
                                {
                                    @*<li><img alt="Formas de Pagamento" src="@item4.URL" /></li>*@
                                    <li><img alt="Formas de Pagamento" src="@item4.URL" /></li>
                                    @*<li><img alt="Formas de Pagamento" src="~/Content/img/conteudo/formas-pagamento/mastercard.jpg" title="Mastercard"/></li>
                                        <li><img alt="Formas de Pagamento" src="~/Content/img/conteudo/formas-pagamento/itau.jpg" title="Itaú"/></li>
                                        <li><img alt="Formas de Pagamento" src="~/Content/img/conteudo/formas-pagamento/elo.jpg" title="Elo"/></li>
                                        <li><img alt="Formas de Pagamento" src="~/Content/img/conteudo/formas-pagamento/boleto.jpg" title="Boleto"/></li>*@
                                }
                            </ul>
                        }
                    }
                </div>
                @if(BLL.AuxiliarCookieBLL.GetExibirRegulamento() == true)
                {
                    <div class="footer-social">
                        <h6><a href="javascript:void(0)" class="collapsed" data-parent="#navFooter" data-toggle="collapse" data-target="#Social"><i class="icon icon-right visible-xs-inline-block visible-sm-inline-block"></i>Redes Sociais</a></h6>
                        <ul id="Social" class="collapse list-horizontal">
                            <li>
                                <a href="https://www.facebook.com/quemdisseberenice?" title="Facebook" target="_blank"><i class="icon icon-facebook"></i></a>
                                <a href="https://www.twitter.com/qdberenice" title="Twitter" target="_blank"><i class="icon icon-twitter2"></i></a>
                                <a href="https://www.plus.google.com/103681384225392027168/about" title="Google+" target="_blank"><i class="icon icon-gplus"></i></a>
                            </li>
                        </ul>
                        <div class="clearfix"></div>
                    </div>
                }
            </li>

            <li class="col-md-3 ofertas">
                <div>
                    <h6>Receba ofertas exclusivas no seu e-mail</h6>
                    <div class="form-group col-xs-12 no-padding">
                        <input type="text" name="Email" id="txtEmailNewsLetter" placeholder="Digite seu e-mail" />
                    </div>
                    <div class="form-group col-md-8 input-left">
                        <input type="text" name="Nome" id="txtNomeNewsLetter" placeholder="Digite seu nome" />
                    </div>
                    <div class="form-group col-md-4 no-padding container-btn-enviar text-right">
                        <a href="javascript:void(0)" title="Enviar" id="btnEnviarNewsletter" class="btn btn-dark">Enviar</a>
                    </div>
                    <p id="erroNewsLetter" class="display-none no-margin-top">Verifique os campos digitados!</p>
                    <p id="msgOkNewsLetter" class="display-none no-margin-top">E-mail cadastrado.</p>
                    <p id="msgErroRequest" class="display-none no-margin-top">Erro ao cadastrar. Por favor tente novamente.</p>
                    <div class="clearfix"></div>
                </div>
            </li>
        </ul>
    </nav>
    <div class="clearfix"></div>
</div>

EDIT

Here is CookieHelper code content:

There are two constructors and Property

//Constructors
public CookieHelper(String CookieName)
    {
        myCookieName = CookieName;          
    }

public CookieHelper(String CookieName, DateTime ExpiresDate)
    {
        myCookieName = CookieName;
        dtExpires = ExpiresDate;
    }

//Property
private static HttpCookie myCookie
    {
        get
        {
            return HttpContext.Current.Request.Cookies[myCookieName] != null ? HttpContext.Current.Request.Cookies[myCookieName] : NewCookie();
        }
        set
        {
            HttpContext.Current.Response.Cookies.Add(value);
        }
    }

And here is basic methods:

public void AddToCookie(String FieldName, String Value)
    {
        HttpCookie myHttpCookie = myCookie;
        myHttpCookie[FieldName] = Value;
        myCookie = myHttpCookie;
    }

public void RemoveCookie()
    {
        HttpCookie myHttpCookie = myCookie;
        myHttpCookie.Value = null;
        myHttpCookie.Expires = DateTime.Now.Date.AddDays(-1);
        myCookie = myHttpCookie;
    }
private static HttpCookie NewCookie()
    {
        HttpCookie newcookie = new HttpCookie(myCookieName);
        if(dtExpires != null)
            newcookie.Expires = (DateTime)dtExpires;
        HttpContext.Current.Response.Cookies.Add(newcookie);
        return newcookie;
    }

What could be happening?
All content inside this Cookie worked fine, and suddenly all Browsers are not stored this specific one.
Can any one help me with this problem?

If needs any further information, please advise me.

bcesars
  • 1,016
  • 1
  • 17
  • 36
  • 1
    I recommend you to use a tool like [fiddler](https://www.telerik.com/download/fiddler/fiddler4). You can see which http request/respose loses the cookie. – Jose M. Mar 02 '16 at 21:07
  • 1
    If you remove all cookies (Campanha and Usuario) and only keep **Rodape**, can you see it then? If you don't se any cookie when removing Campanha and Usuario, maby you accidentally overrite the Rodape cookie somewhere? Have you also checked what date `... = (DateTime)dtExpires` has when you set the Rodape cookie? – Binke Mar 02 '16 at 22:01

2 Answers2

2

Not sure about your code in CookieHelper but I can't see that you'r setting an expiration or adding the cookie to the response. Those are two very important parts to using cookies so if they are missing, try to do something like this

public static void SetCampanhaInstitucional(List<CampanhaInstitucionalModel> CampanhaInstitucional)
{
    if (CampanhaInstitucional != null)
    {
        string campanha = JsonConvert.SerializeObject(CampanhaInstitucional);
        HttpCookie theCookie = new HttpCookie(cookienameRodape, campanha);
        theCookie.Expires.AddDays(7); //Keep the cookie alive for 7 days
        HttpContext.Response.Cookies.Add(theCookie); //add the cookie to the response

        //alternatively you could also use
        //HttpContext.Response.SetCookies(theCookie);
    }
}

If your having trouble with using HttpContext.Response.Cookies.Add(theCookie); you might need to set the cookie using Response.SetCookie(theCookie) as per This answer to a cookie problem

Also, how much data are you storing? Cookies are not ment to store alot of data and most browsers support up to 4096 bytes or 4kb. This is however for all cookies on the domain, so if you have 2 cookies using the 4kb, then adding another cookie will result the loss off cookies.
I can see from the screenshot that you are not using all of the available space, but as the Rodape cookie is not present, I have now idea of how big than one might be. Try just adding the Rodape cookie and see if it persists and check the size of it.

Community
  • 1
  • 1
Binke
  • 897
  • 8
  • 25
  • Are you saying if that all these three cookies is bigger than 4kb some data will be lost? Or each cookie can support 4kb? – bcesars Mar 02 '16 at 18:50
  • I Edited my question adding content inside CookieHelper. It might help with this information. – bcesars Mar 02 '16 at 20:47
  • 1
    To be safe, all cookies total size should not exceed 4kb, but that is including name, expire date and all other properties. This is however different for different browsers. http://stackoverflow.com/a/4604212/2960852 – Binke Mar 02 '16 at 21:53
  • Sudddenly all browsers remove Cookie contents that exceed 4kb. I discovered that all cookieRodape is taking too much of data storing. Thanks @Binke. – bcesars Mar 03 '16 at 19:52
0

There are numerous possible causes for what you're seeing. To find the specific cause for your case, I would start by setting breakpoints in the code in any place where the value of the cookie gets set or reset. By running the code in a debugger, you can see if that code gets called at unexpected times. Repeat the steps to reproduce the problem, taking note of any unexpected calls to the code that change the cookie value. See what this reveals.

gpersell
  • 84
  • 1
  • 10
  • 1
    I've made it. When I debugged, All footer content was showed on _footer.cshtml. And all this content was there. After that, nothing else will be executed and all Cookie from cookienameRodape gone. – bcesars Mar 01 '16 at 18:01