Dan Atkinson
Dan Atkinson

Reputation: 11728

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?!

Upvotes: 5

Views: 4192

Answers (3)

Chuck Conway
Chuck Conway

Reputation: 16435

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.

Upvotes: 1

yfeldblum
yfeldblum

Reputation: 65445

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

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1502126

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 :)

Upvotes: 13

Related Questions