My research indicates that, if I create a cookie and don't set the expiration date, it will expire when the browser is closed.

So I created a cookie like this:

Response.Cookies.Set(new HttpCookie("MyKey", "X"));

But when I close the browser and then reopen it, the following expression equals true:

Request.Cookies["MyKey"] != null

How can I have the cookie expire when the browser session ends?

Note: For my purposes, using static data instead of a cookie seems ideal. But my understanding is that an ASP.NET can restart for a variety of reasons, and that could pull the rug out from under the current user if I lost this setting.

You can catch this on the next Session_start event. If you already have an authenticated user immediately when a brand new session starts, then you must have gotten that info from a stale cookie. Just null out the user info and let Login redirects take care of the rest.

Something like this in global.asax.cs:

<!-- language: lang-cs -->
protected void Session_start()
{
    // starting a session and already authenticated means we have an old cookie
    var existingUser = System.Web.HttpContext.Current.User;
    if (existingUser != null && existingUser.Identity.Name != "")
    {
        // clear any existing cookies
        IAuthenticationManager authMgr = System.Web.HttpContext.Current.GetOwinContext().Authentication;
        authMgr.SignOut("MyCookieType")

        // manually clear user from HttpContext so Authorize attr works
        System.Web.HttpContext.Current.User = new ClaimsPrincipal(new ClaimsIdentity());
    }

}
  • Code may vary somewhat depending on how you're authenticating users

See also: