Hamdan Sultan Hamdan Sultan - 1 year ago 61
ASP.NET (C#) Question

cookie is showing null value for first time and after coming again to that page, i can see cookie value. Asp.net c#

I am developing a website in which user has to buy a subscription, what i am trying to do is that when user log in to my website for buying subscription i save his/her email id in a cookie and then he/she is redirected to paypal and after paying money he comes back to success page of my website and there i retrieves the cookie of his email id to update database but there for first time i gets null value and if i repeat the same process again i can read the value in cookie which i stored. On my localhost this problem wasn't coming but when i published the website this problem came. help me out
The code i am using to store the cookie

Response.Cookies["useremail"].Value = Session["user_id"].ToString();
Response.Cookies["useremail"].Expires = DateTime.Now.AddDays(1);

The code i am using to retrieve the cookie

if (Request.Cookies["useremail"] != null)
Label1.Text= Server.HtmlEncode(Request.Cookies["useremail"].Value);

On the browser i have seen that cookie is saved.

Answer Source

In a nutshell this is what I would expect to see in your code but I do not so you can try this and replace it with the proper variables etc to make your code work. I test this on my test server and it works so you can follow the same pattern.

string myCookieName = "abcd";
HttpCookie aCookie = new HttpCookie(myCookieName);
aCookie.Value = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);