Wednesday, February 18, 2009

Getting and Setting cookies

I was recently having a lot of trouble trying to set and read a cookie in asp.net.  I discovered that my big issue was not correctly using the Request and Response objects.  The Request object is only used for retrieving a cookie, while the Response object is only used for creating a cookie.

Another little anomaly I found.  Apparently the client doesn't send the experation date of a cookie when it sends the cookie to the server.  So, in asp.net when retrieving a cooky the experation date will always be MinDate even if the date is set correctly.

    HttpRequest oRequest = System.Web.HttpContext.Current.Request;
    HttpResponse oResponse = System.Web.HttpContext.Current.Response;

      HttpCookie oCookie = oRequest.Cookies[ConfigurationManager.AppSettings["anonUserCookie"]];
      if (oCookie == null) oCookie = new HttpCookie(ConfigurationManager.AppSettings["anonUserCookie"], Guid.NewGuid().ToString());
      oCookie.Expires = DateTime.UtcNow.AddMonths(1);
      oResponse.Cookies.Add(oCookie);

No comments:

Post a Comment

Please leave your thoughts, I love hearing what you got out of the post. Spam comments will be removed.