1

I am using c# and mvc. I am trying to write a cookie to the user browser. But after a refresh of the browser the cookie disappears.

This is my code for writing the cookie:

 movieCookie = new HttpCookie(cookieName);
 movieCookie.Value = "test;
 movieCookie.Expires = DateTime.Now.AddDays(30);
 //add the cookie 
 HttpContext.Current.Response.Cookies.Add(movieCookie);

and the one for reading the cookie:

//check if such cookie exist
HttpCookie movieCookie = null;
if (HttpContext.Current.Request.Cookies.AllKeys.Contains(cookieName))
    movieCookie = HttpContext.Current.Request.Cookies[cookieName];

Another thing to add is that when I searched "AllKeys" like so:

HttpContext.Current.Request.Cookies.AllKeys

it shows an empty string array, for some reason. any ideas?

mashta gidi
  • 849
  • 1
  • 10
  • 30
  • If you are using a recent version of IE, have you used F12 to see what is being sent between the server and client? – HABO Jul 24 '12 at 12:45
  • You say the cookie disappears, so you could see the cookie already in the browser? Can you say, in which context the cookie was created? If the context for example is "/" it should be readable by all pages under the current domain. Maybe the default context for your app is set too deep. And thsi forbids other pages to read the cookie. – Kai Mattern Jul 24 '12 at 12:47

2 Answers2

1

Some possibly silly questions

  • Check your web-servers time and date, are they set correctly, if they are (in your case) 2 years out it will expire cookies immediately.

  • Check that cookieName is the same

  • Check that after setting the cookie to the response your not redirecting before the cookie is set. For a cookie to be set you need to set headers and push them out.

John Mitchell
  • 9,653
  • 9
  • 57
  • 91
  • I changed the cookie expiration to 30 days and checked the cookie name and it's the same. Didn't understand your third comment - after I am setting the cookie I am returning to the view (Mvc) and then sending a request from the client to the controller again and from there to the cookies function... – mashta gidi Jul 24 '12 at 13:51
0

I solved it. It appears that in MVC the "return view" after the cookie creation, cause the cookie not to be saved.

mashta gidi
  • 849
  • 1
  • 10
  • 30