Breaking News

Editors Picks

Wednesday, April 3, 2013

How to create a new session in ASP.NET programmatically


If you want to create a new session (open a new window in a new session), without disturbing/loosing the other one, you will have to use the SessionIDManager.
Here is a short example (this will only work with <sessionState cookieless=”true” /> in the web.config):


protected void Page_Load(object sender, EventArgs e)
{
            if (!IsPostBack)
            {
                string ss1 = Session.SessionID;
                Session.Abandon();              
               Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
            }
           
}
This code example clears the session state from the server and sets the session state cookie to null. The null value effectively clears the cookie from the browser.

When a user does not log off from the application and the session state time-out occurs, the application may still use the same session state cookie if the browser is not closed. This behavior causes the user to be directed to the logon page and the session state cookie of the user to be presented. To guarantee that a new session ID is used when you open the logon page (login.aspx), send a null cookie back to the client. To do this, add a cookie to the response collection. Then, send the response collection back to the client. The easiest way to send a null cookie is by using the Response.Redirect method. Because the cookies collection always has a value for the ASP.NET_SessionId, you cannot just test if this cookie exists because you will create a Response.Redirect loop. You can set a query string on the redirect to the logon page.

Or, as illustrated in the following code example, you can use a different cookie to tell if you are already redirected to the logon page. To help enhance security and to make sure that no one tries to open the logon page by using a second cookie together with the ASP.NET cookie, the following code example uses the FormsAuthentication class to encrypt and decrypt the cookie data.

No comments :

Post a Comment

Contact Us

Name

Email *

Message *