Reputation:
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?
Upvotes: 11
Views: 9599
Reputation: 8568
At first I was also disappointed that request cookies don't have the Expires
value, but after debugging using Fiddler2, I know that the http protocol does not include any Expires
value for request cookies. The .NET Framework has no way of exposing Expires
value for request cookies.
If you use Fiddler between your app and the browser, you can see the response cookie sent correctly to the browser with all properties. However, the request cookie in the http headers doesn't have the expires value, it only exposes cookie name and value. Browsers are required to send this request header, as specified in the http standard. The reason why could be to minimize size and web servers don't need to check anything other than the values.
So you do not need to check the expires
value on web request, because it is what you set it to be on some earlier web response. If you receive the cookie back, that means the cookie is not yet expired. Once you set the expires
value, the browser will handle the expiration. If you want to change the expires, just set the new value on the response.
Upvotes: 5
Reputation: 189457
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.
Upvotes: 22