tags:

views:

538

answers:

2

Hi, I am setting a cookie with:

HttpCookie cookie = new HttpCookie("simpleorder");
cookie.Expires = DateTime.Now.AddYears(1);
cookie["order"] = carModel.ToString();
cookie["price"] = price.ToString();
Response.Cookies.Add(cookie);

But when I check it a few seconds later it is expired and the expiration date is set to {01-01-0001 00:00:00}. I try to retrieve the code by

 HttpCookie cookie = Request.Cookies["simpleorder"];
 if (cookie != null && cookie.Expires > DateTime.Now)...

I don't clear the cookie any place, so I don't know why it expires?

+4  A: 

This is common mis-understanding. The Request cookie collection represents the cookies included in the requests cookie header. Such cookies do not contain any info regarding when they expire. Strictly speaking .NET ought to have used two different types (RequestCookie and ResponseCookie) but instead chose to use the same type for both circumstances.

The Expires value only makes sense when adding cookies to the response.

AnthonyWJones
So the only way to check if a cookie is expired is to check if it exists?
Yes thats about it.
AnthonyWJones
A common solution, if you need to know the expiry date, is to save it as a value inside the cookie. It could suddenly get out of sync, but if it's a httponly cookie, you have the power to make sure it doesn't happen ;)
Per Hornshøj-Schierbeck
A: 

Hi,

At first I also disappointed why Request cookie doesn't have the actual Expires value. After debugging the http by using Fiddler2. I know that .NET was not wrong, instead, http protocol is the answer why Request cookies behaving like that.

If you use Fiddler between your app and the browser. You can see the Response cookie sent correctly to browser with all domain, path, expires, secure and httponly. However next Request cookie in http cookie header doesn't have the expires value, it only cookie name and value. Browser responsible to send this request header and I believe that is because http protocol. The reason why is because to minimize size and web server doesn't need to check it since they actually set all the values. They should notice.

So you no need to check the expires value on web request since you already know the date. Just, if you receive the cookie back that means the cookie is not yet expired. Once you set the expires, browser will handle the expiry. If you want to change the expires, just set the new value on the response.

CallMeLaNN

CallMeLaNN