views:

181

answers:

3

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

+3  A: 

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

Jon Skeet
There is nothing in the Response.Cookies.
Dan Atkinson
It's not very clear what's going on. You're setting the cookies - are you then examining them in the next request? I wouldn't expect anything in Response.Cookies unless you're adding them.
Jon Skeet
My action is basically a SetEnvironmentMode action. In this action, the cookie is set, and returns a RedirectToAction to GetEnvironmentMode.
Dan Atkinson
I see my problem here, and I understand what you're saying. What I was trying to do was to have a expiry time (which works), but also, in my GetEnvironmentMode view, show the user how much longer was left before that cookie expires.
Dan Atkinson
I think you'll have to include something in the cookie value to remember that, I'm afraid.
Jon Skeet
A: 

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

Justice
A: 

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.

Chuck Conway
Well, it's MVC, and I'm doing a RedirectToAction.
Dan Atkinson