Andrew Sklyar
Andrew Sklyar

Reputation: 293

Cookies Max-Age in Web Forms

Is it possible to set Max Age for Cookies in Web Forms Application? I know, that it's okey to set Expire, but is there a way to set Max Age?

Upvotes: 2

Views: 3011

Answers (1)

Byron Katz
Byron Katz

Reputation: 510

Asp.Net doesn't specifically provide this property on HttpCookie, probably because they are very Microsoft-centric, and IE doesn't support max-age (as least, as of IE11)

However, you can still do it. Here's some code demonstrating the proper and invalid ways to set this cookie with max-age:

// doesn't work:
var mytestcookie = new HttpCookie("regular_httpcookie", "01");
mytestcookie.Values.Add("max-age", "300");
Response.Cookies.Add(mytestcookie);

// *does* work:
Response.Headers.Add("set-cookie", "testingmaxage=01;max-age=300; path=/");

And it renders like this in the HTTP response:

Set-Cookie  testingmaxage=01;max-age=300; path=/
X-AspNet-Version    4.0.30319
Set-Cookie  regular_httpcookie=01&max-age=300; expires=Fri, 10-Jun-2016 15:02:15 GMT; path=/

As you can see above, if you are also setting cookies using HttpCookie, this will create a second "set-cookie" header on the response , but the browser won't mind, it will just add it to the list of cookies.

I tested on IE11 and Chrome and this is a non-issue - the cookies will all go in, as long as they have differing names. If the cookie name conflicts with one already set in HttpCookies, the last one in wins. Check out the text of your HTTP response to see which one goes in last. (Best to simply make sure they don't conflict though)

As I mentioned at the beginning, when testing on IE11, I noted that it's ignoring the max-age property of the cookie. Here's a link to a way to settle that issue: Set-Cookie: Expire property, clock skew and Internet Explorer issue

Upvotes: 2

Related Questions