set cookie to expire at end of session?

You’re talking about a non-persistent cookie. By default sends cookies in that way. The main difference between them are that a persistent cookie has an expires value set.

So, if you don’t want the cookie to persist, then do not set the expires value.

That said, the cookie will remain in memory until the browser is actually closed. Let’s say they browse to your site and you set a non-persistent cookie. They do things and browse away. Later they, using the same browser instance, come back to your site. The cookie will still be there.

Now, if they closed the browser at any point, then the cookie would be flushed out.

Point is, don’t set the expires header. Especially not to when the session date expires. Session dates are generally only 20 or so minutes in the future, but the expiration date rolls forward as the user browses through your site.

===== update =====

I used the following code for testing:

    protected void Page_Load(object sender, EventArgs e) {
        if (!Page.IsPostBack) {
            HttpCookie c = Request.Cookies["test"];
            if (c != null) {
                Response.Write(String.Format("test value is {0} <br />", c.Value));
        } else {
            HttpCookie c = new HttpCookie("test");
            c.Value = "HERE IT IS";

    protected void Button1_Click(object sender, EventArgs e) {
        Response.Write("clicked<br />");

the .aspx file simple had a button which fired that button1_click handler. When I initially browse to it using any of the latest browsers (ie, firefox, chrome) there is no cookie. After I click the button a cookie is set. Then I closed the browser completely, reopened and browsed back to the site. In all cases the cookie was gone.

Leave a Comment