ASP.NET resseting SessionID cookie when cookie expiration date is set
- by Sergej Andrejev
I have two pages: Default.aspx and WebForm1.aspx. One of these pages stores a session variable which works fine until I add code which ads expiration date to SessionID cookie.
What happens is:
Open default.aspx
Set-Cookie ASP.NET_SessionId=14jhsdfq23jkh13jkh12k1;
expires=Fri, 19-Mar-2010 07:31:47 GMT;
path=/
Click on link to open WebForm1.aspx
No cookies set
Click on link to open Default.aspx (Cookie is reset)
Set-Cookie ASP.NET_SessionId=;
expires=Fri, 19-Mar-2010 07:31:47 GMT;
path=/
So the question would be how should I set SessionID cookie expiration date correctly?
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lnk.Click += new EventHandler(lnk_Click);
Session["t"] = Guid.NewGuid();
Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddDays(2);
}
void lnk_Click(object sender, EventArgs e)
{
Response.Redirect("WebForm1.aspx");
}
}
}
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:LinkButton runat="server" ID="lnk" Text=">>>" />
</div>
</form>
</body>
</html>
WebForm1.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lnk.Click += new EventHandler(lnk_Click);
}
void lnk_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
}
}
WebForm1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:LinkButton runat="server" ID="lnk" Text=">>>" />
</div>
</form>
</body>
</html>