3

Coming from a non-web background I'm struggling with cookie uniqueness. When I read and write to a cookie named CustomerCode I find multiple cookies with the same name in my cookie collection(s). How can this be avoided?

duplicate request cookies

duplicate response cookies

Database rows use a primary key to ensure uniqueness. Is there an equivalent for cookies? I'm using this "Reusable Cookie Container" code to simplify writing to a cookie:

Master.Cookies.CustomerCode = SessionWrapper.CustomerCode;

Then in my SessionWrapper I restore session variables from the cookie(s)

public static void InitiateSessionVariablesFromCookies(IAppCookies appCookies) {
    if (SessionWrapper.CustomerCode == null && appCookies.CustomerCode != null) {
        SessionWrapper.CustomerCode = appCookies.CustomerCode;
    }...

The cookie collection contains CustomerCode multiple times so the wrong value is being passed to the session variable. If this question is difficult to answer without seeing all of my code please describe the proper / best way to set cookies and then read them back into session variables (or include a link to help me out).

Thanks in advance.

DeveloperDan
  • 4,626
  • 9
  • 40
  • 65

1 Answers1

2

If you have different expiration date/times you can get "duplicates".

HttpCookie Temp = new HttpCookie("MyName", "123");
Temp.Expires = DateTime.Now.AddMinutes(5);

Response.Cookies.Add(Temp);

This code will create a new cookie each time it runs with the same name and value.

Steve Wellens
  • 20,506
  • 2
  • 28
  • 69
  • I believe that solves my problem. I had been setting Expires to DateTime.Now.AddDays(10) and the time portion was different each time causing "duplicate" cookies. I've changed setting Expires to DateTime.Today.AddDays(10). I have meetings now but will mark this as the answer later if that worked. Thanks! – DeveloperDan Jun 28 '12 at 15:49
  • Here's a nicely written article on ASP.NET Cookies which details potential problems and how to work around them: http://www.codeproject.com/Articles/3106/On-The-Care-and-Handling-of-Cookies. I landed on it after reading this: http://stackoverflow.com/questions/198295/asp-net-cookie-expiration-time-is-always-1-1-0001-1200-am – DeveloperDan Jul 19 '12 at 19:21