How to make an ASP.NET session cookie expire with

2019-06-28 07:16发布

I have created an HttpCookie in order to share data across a subdomain :

HttpCookie cookie = new HttpCookie("sessionGUID");
cookie.Value = value;
cookie.Domain = ".example.com";

Response.Cookies.Set(cookie);

I carelessly assumed since it is a 'session' cookie (no expires) that it would expire along with my ASP.NET session. Of course to the browser this is a 'browser session' cookie and not linked to the ASP.NET session.

What I want to do is expire these 'browser session' cookies along with the ASP.NET session.

i think I just need to set Expires to the same value as the ASP.NET session. How would i determine this programatically?

1条回答
可以哭但决不认输i
2楼-- · 2019-06-28 07:20

If they just need to be close then something like this:

int expirationMinutes = Session.Timeout;
if (System.Web.HttpContext.Current.Response.Cookies["monster"]!=null)
{
    System.Web.HttpContext.Current.Response.Cookies["monster"].Expires =
                                 DateTime.Now.AddMinutes(expirationMinutes);
}

The session timer resets everything the user posts or gets, so since code is executing on the server right now, the remaining time on the current session is Session.Timeout, say 20 minutes.

In 20 minutes, the cookie will not be accepted and you'll have to issue a new one.

查看更多
登录 后发表回答