user2842987
user2842987

Reputation: 33

My Session variable is always null

I'm creating a movie ticket reservation project. I want to get username from page1 and display it on page2 (using session variable)

Page1:

 string uname = TextBox1.Text;
 Session["UName"] = uname;
 Session.Timeout = 30;

Page2:

 if ((string)Session["UName"] != null)
        {
            string user = (string)Session["UName"];
        }

and I placed a sign out button in page2 to remove session variable value. But the session variable is always null. I've already used cookies in the page1 and will this be a cause? or what else? Please Help. Thanks in advance.

Upvotes: 0

Views: 7301

Answers (3)

user3582680
user3582680

Reputation: 11

I also had same problem, I was toggling between debugging two different sites on localhost and there were two cookies for the session ID.

I deleted the cookies via Chrome's developer tools [Press F12 in Browser]->Application->Storage->Cookies

Upvotes: 0

Robert
Robert

Reputation: 3302

See this answer on when the Session can be null:

What should I do if the current ASP.NET session is null?

I personally often ran into this issue when I was using async requests with completion callback. In these callbacks I wanted to set something in the session and it was null.

Upvotes: 1

James Johnson
James Johnson

Reputation: 46047

This usually occurs when doing a Response.Redirect after setting the session variable. You can work around this issue by calling the overload instead:

Response.Redirect("...", false); // false = don't stop execution

//causes ASP.NET to bypass all events and filtering in the HTTP pipeline
//chain of execution and directly execute the EndRequest event
HttpContext.Current.ApplicationInstance.CompleteRequest();

The underlying issue is a ThreadAbortException which is often ignored because it doesn't break the application. This is a known issue, and you can learn more about it here: http://support.microsoft.com/kb/312629.

Side Note

On a side note, you shouldn't be resetting your Session.Timeout value in the code like that. I can't be sure, but that may also have an adverse affect on your logic. Instead, you should specify the session timeout in the web.config under the system.web section:

<sessionState timeout="60"  />

Upvotes: 1

Related Questions