Reputation: 776
I am new to ASP.NET sessions, and am noticing that the session key/variables stored in the Session are expiring after PostBack.
In the code below, during the first page load, I save some XML to a Session key. Then, if a user clicks on a radio button on the web page, it causes a PostBack. After the PostBack, my Session variable that I stored with the XML data is now NULL.
I thought it may have something to do with the Session.Timeout = 60, but I noticed that even if the user clicks the radio button within the first 10 seconds of first page load, the Session variable is still NULL.
In the doStuff() below, xmlDoc is NULL.
public partial class InstallmentBillingPortal : System.Web.Ui.Page
{
XmlDocument xmlDoc
{
get
{
return Session["xmlDocKey_3069"] == null ? null : (XmlDocument)Session["xmlDocKey_3069"];
}
set
{
Session["xmlDocKey_3069"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
Session.Timeout = 60;
if (!this.IsPostBack)
{
var xml = File.ReadALlText(Server.MapPath(@"request.xml"));
xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
}
else
{
doStuff();
}
}
void doStuff()
{
if (xmlDoc != null)
{
// do something
}
}
}
Upvotes: 0
Views: 1171
Reputation: 62290
Data stored inside SessionState available til user closes the browser or session timeout. Therefore, you want to check xmlDoc == null
instead of IsPostBack
.
Do not set SessionState timeout inside a page. Instead, you want to set it inside web.config. For example, 60 minutes -
<configuration>
<system.web>
<sessionState timeout="60"></sessionState>
</system.web>
</configuration>
XmlDocument xmlDoc
{
get { return (XmlDocument) Session["xmlDocKey_3069"]; }
set { Session["xmlDocKey_3069"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (xmlDoc == null)
{
var xml = File.ReadAllText(Server.MapPath(@"request.xml"));
xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
}
doStuff();
}
FYI: If you just want data to live during postbacks, you might want to consider using View State.
Upvotes: 1
Reputation: 1
asp.net provides the file name global.asax where you can maintain values of the such types of sessions.Try using the files because its scope till main session of page expires.And you would able to keep wath on time of sessions
Upvotes: 0