Sarah Weinberger
Sarah Weinberger

Reputation: 15561

Cookies are not persistent

I am using ASP.net to store cookies. I save a cookie on a popup in the code behind (C#). If I request the cookie, before the popup closes, then the cookie is there, however closing the popup and going back into it and looking at the cookie in the Page_Load event shows no cookie. How do I get it to persist?

Following code in popup OK button

// Set the cookie.
this.Response.Cookies["UserData"].Secure = true;
this.Response.Cookies["UserData"]["UserId"] = iId.ToString();
this.Response.Cookies["UserData"]["UserEmail"] = strEmail;
this.Response.Cookies["UserData"].Expires = DateTime.Now.AddDays(1);

Following code placed in Page_Load event

// Get the cookie.
if (null != this.Request.Cookies["UserData"])
{
    // Transmit the cookie information using SSL. Note, the cookie data is still in plain text on the user's computer.
    this.Request.Cookies["UserData"].Secure = true;

    // Extract: Email
    String strEmail = this.Server.HtmlEncode(oPage.Request.Cookies["UserData"]["UserEmail"]);
}

Naturally, the very first time will show nothingness, however subsequent loads should show the cookie.

I had slightly better luck with using .Values["Subitem"] = "whatever", but that yielded the base to persist, but all subitems to disappear.

Upvotes: 1

Views: 216

Answers (1)

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

One possible reason: your page is HTTP, but you are setting cookies to be HTTPS-only. So browser simply does not send them back with HTTP request to your site.

Use Fiddler (or other HTTP debugger) to see if cookie is correctly send in the response (and next request).

Upvotes: 2

Related Questions