2

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?

Andrew Sklyar
  • 293
  • 4
  • 16
  • i'm not sure what the difference is. – wazz Dec 06 '15 at 00:32
  • what do you mean by Max Age? this term is usually related to cache. – wazz Dec 06 '15 at 00:49
  • 1
    @wazz cookies can have this attribute as well and this serves good when the time on server and client is different, because in case of max-age, unlike with expire, their expiration date will be independent of client time – Andrew Sklyar Dec 06 '15 at 13:59
  • tnx, i'll have to read up. are you saying you want to set the value in code-behind (not javascript or something else)? – wazz Dec 06 '15 at 21:25

1 Answers1

2

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

Community
  • 1
  • 1
Byron Katz
  • 492
  • 5
  • 10