Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpCookie with Expires set returns DateTime.MinValue

I'm seeing something of an oddity when setting a cookie...

Action:

string cookieName = "foo";
string cookieValue = "bar";

//Set a cookie in the response, along with the Expires.
this.ControllerContext.HttpContext.Response.Cookies.Add(
  new HttpCookie(cookieName, cookieValue)
  {
    Expires = DateTime.Now.AddHours(1)
  }
);

When debugging, I can see that this new cookie has an expiry of one hour in the future, and yet, when I look at the cookie in the view, the expiry isn't there...

View:

<%= Request.Cookies.Get("foo").Value %>

Returns bar.

<%= Request.Cookies.Get("foo").Expires %>

Returns 01/01/0001 00:00:00

Any ideas?!

like image 876
Dan Atkinson Avatar asked Nov 04 '09 21:11

Dan Atkinson


3 Answers

You're looking at the request - which doesn't contain an expiry time. The server tells the client when the cookie should expire; there's no need for the client to tell the server as well :)

like image 59
Jon Skeet Avatar answered Oct 14 '22 22:10

Jon Skeet


Response.Cookies is a very different thing from Request.Cookies.

like image 32
yfeldblum Avatar answered Oct 14 '22 23:10

yfeldblum


Two things: First, if you are looking at the Request before the Response has been pushed to the client, then the Request will not have your updates.

Second, if you are setting a cookie and then using a Response.Redirect, your cookie values might not have been pushed to the client. Under the covers Response.Redirect calls "Thread.Abort()", which is kills the thread.

like image 42
Chuck Conway Avatar answered Oct 14 '22 22:10

Chuck Conway