views:

4006

answers:

2

I have a ASP MVC App with some seemingly simple code to save and retrieve cookies but for some reason they won't persist. The code in the controller is :

if (System.Web.HttpContext.Current.Response.Cookies["CountryPreference"] == null)
{
    HttpCookie cookie = new HttpCookie("CountryPreference");
    cookie.Value = country;
    cookie.Expires = DateTime.Now.AddYears(1);
    System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
}

And to load it again :

if (System.Web.HttpContext.Current.Request.Cookies["CountryPreference"] != null)
{
    System.Web.HttpContext.Current.Request.Cookies["CountryPreference"].Expires = DateTime.Now.AddYears(1);
    data.Country = System.Web.HttpContext.Current.Request.Cookies["CountryPreference"].Value;
}

For some reason the cookie is always null?

A: 

Your code looks fine, the only thing is that you can not change the expires in the request collection.

Anyway, this is the code I use (in VB)

 Dim cookie As HttpCookie
 cookie = Current.Request.Cookies.Get("CountryPreference")
 If not cookie Is Nothing Then
    CountryID = CType(cookie.Value, Integer)
 end if

It only changes the .get part, but it should be the same.

Eduardo Molteni
The code may "look" fine, but have you actually tried to run and debug it?
Seventh Element
+17  A: 

The problem lies in following code:

if (System.Web.HttpContext.Current.Response.Cookies["CountryPreference"] == null)

When you try to check existence of a cookie using Response object rather than Reqest, ASP.net automatically creates a cookie.

Check this detailed post here. http://chwe.at/blog/post/2009/01/26/Done28099t-use-ResponseCookiesstring-to-check-if-a-cookie-exists!.aspx