C# – session expiring and throwing exception

asp.netc++session

I have a problem with session expiry. Firstly it expires every 20 minutes and it throws an error…

I tried to fix it by:

if (Session["userName"].ToString() == null)
{
   Session.RemoveAll();
   Response.Redirect("~/Login.aspx?sessionError=" + "*Session Expired on pageload PleaseLog in again");
}

But I get the following error:

Object reference not set to an instance of an object.

My stack trace is:

[NullReferenceException: Object reference not set to an instance of an object.]
copiunGUI.Site1.checksession() in C:\Users\jagmit\Documents\Visual Studio 2008\Projects\copiunGUI\copiunGUI\Site1.Master.cs:224
copiunGUI.Site1.TreeViewMain_Unload(Object sender, EventArgs e) in C:\Users\jagmit\Documents\Visual Studio 2008\Projects\copiunGUI\copiunGUI\Site1.Master.cs:210
System.Web.UI.Control.OnUnload(EventArgs e) +8681754
System.Web.UI.Control.UnloadRecursive(Boolean dispose) +252
System.Web.UI.Control.UnloadRecursive(Boolean dispose) +188
System.Web.UI.Control.UnloadRecursive(Boolean dispose) +188
System.Web.UI.Control.UnloadRecursive(Boolean dispose) +188
System.Web.UI.Control.UnloadRecursive(Boolean dispose) +188
System.Web.UI.Page.UnloadRecursive(Boolean dispose) +23
System.Web.UI.Page.ProcessRequestCleanup() +43

My web.config is:

<authentication mode="Forms">
    <forms loginUrl="Login.aspx" defaultUrl="~/Default.aspx" name="Cookie" timeout="10080" path="/">
    </forms>
</authentication>
<authorization>
    <deny users="?"/>
    <allow users="*"/>
</authorization>

Please help…….

Thanks

Thanks for ur input guys…

I tried this:

if (Session["userName"] == null)
{
   Session.RemoveAll();
   Response.Redirect("~/Login.aspx?sessionError=" + "*Session Expired on pageload PleaseLog in again");
}

But i get the error:

Response is not available in this context.

Best Solution

The problem is here:

if (Session["userName"].ToString() == null)

When Session["UserName"] is a null object reference, you can't rightly call .ToString() on it.

Try this instead...

if (Session["userName"] == null)...