user2483797
user2483797

Reputation: 169

Don't redirect after setting a Session variable

I'm facing a problem when redirecting to a page. Please have a look at my code and how i may solve it. The manifest is that after saving variables in session and redirect to a new page, the session variables are lost, and a new sessionId is created. I am a novice. Please advice.

Login.aspx:

Util.IsAdminUser= false; // save in session Util.IsAdminUser
Util.IsSpecialUser = true; //save in session Util.IsSpecialUser
Response.Redirect(Pages.SelectAccounts, false);
return;

SelectAccounts.aspx:

Page_Load(object sender, EventArgs e)
  {
    if (!Util.IsAdminUser)  // error of null, session is lost
    {
       ...
       ...
    }
   }
 protected void Session_Start(object sender, EventArgs e)
        {
             LoggerNet.Info("SessionId:" + Session.SessionID); 
        }

Thank you in advance

Upvotes: 1

Views: 6206

Answers (1)

VMAtm
VMAtm

Reputation: 28355

According the MSDN article:

For mobile pages, if your application relies on cookieless sessions, or might receive requests from mobile devices that require cookieless sessions, using a tilde (~) in a path can create a new session and potentially lose session data.

To set a property on a mobile control
with a path such as ~/path, resolve the path using ResolveUrl
~/path before assigning it to the property.

So, if you have a ~ in your Pages.SelectAccounts constant, you may have a new Session each time. Try to add the ResolveUrl method before the redirect.
May be you should switch to the Server.Transfer method, which is perform similar action, but without the roundtrip to the client. Please refer to the MSDN for more information:

How to: Redirect Users to Another Page
Correct use of System.Web.HttpResponse.Redirect


Update

Also you should check this answer:

ASP.NET: Session.SessionID changes between requests

Try to use the Session object in your Global.asax file for handling the Session_Start event - this will lock the SessionId for current user, and it wouldn't be changed again.


Update #2:

You must set some variable into the Session object, like this:

protected void Session_Start(object sender, EventArgs e)
{
    LoggerNet.Info("SessionId:" + Session.SessionID);
    Session["LastVisitDate"] = DateTime.Now;
}

Only after setter for the Session object is being called you'll have the persistent SessionId for the user.

Upvotes: 1

Related Questions