Reset sessionid in asp.net by code

Source: Internet
Author: User

Many people may think that the sessionid will not change without restarting the browser. In fact, you can reset the sessionid through the code ~~ Roar:

ASP. NET session status is a technology that allows you to store server-side and user-specific data. Web applications can use these data to process requests from users whose session status is instantiated for them. The session Status user is identified by the session ID. Transmit the session ID using one of the following methods:

Session ID is part of the Cookie sent to the user's browser.
The session ID is embedded in the URL. This technology is also known as "cookieless sessions ".

Session ID is a 120-bit random number represented by a string of 20 characters. The string format can be included in the URL without URL encoding. For example, you can use a string in a non-Cookie Session. The most common method for transferring session IDs is to store session IDs by using cookies.

When a user opens a Web browser for the first time and switches to an implemented ASP. NET session status, a website named "ASP. NET_SessionId "and contains a Cookie consisting of 20 characters.

When a user browses in the same DNS domain, the Web browser will continue to send this Cookie to the source domain.

For example, app1.tailspintoys.com and app2.tailspintoys.com are both ASP. NET applications. If the user switches to app1.tailspintoys.com and app2.tailspintoys.com successively, the two applications use the same Cookie and session ID to track the user's session Status in each application. Applications do not share the same session status. Only session IDs are shared between applications.

Therefore, session IDs can be reused for multiple reasons. For example, if you reuse a session ID, you do not have to perform the following operations:

When a valid session ID is provided to you, a new encrypted unique session ID is created.
Creates a session ID for each ASP. NET application in a single domain.

When the Web application requires logon and provides the logout page or option, we recommend that you clear the session status after the user logs out of the website. To clear the Session Status, call the "Session. Abandon" method. You can use the "Session. Abandon" method to refresh the Session status without waiting for the Session status to time out. By default, the timeout period is 20 minutes. This expiration period is refreshed whenever a user sends a request to the website and provides a session ID Cookie. The "Abandon" method sets a flag in the session state object that indicates that the session state should be abandoned. The flag is checked and processed at the end of the page request. Therefore, after calling the "Abandon" method, you can use session objects on the page. Once page processing is completed, the session will be deleted.

When the in-process session Status mode is used, these session Status objects are stored in HttpCache. When the following conditions are met, HttpCache supports the callback method:

The cache item is deleted.
The session Status manager registers the "Session_OnEnd" event handler to be called when a cache item is deleted.

When the session Status manager deletes the session Status objects that reside in the cache, The HttpCache manager calls all registered callbacks. In fact, this action will trigger the "Session_OnEnd" event handler.

When you cancel a session, the session ID Cookie is not deleted from the user's browser. Therefore, once a session is abandoned, any new request to the same application uses the same session ID, but has a new session Status instance. At the same time, if a user opens another application in the same DNS domain, the user will not lose the session status after the "Abandon" method is called from one application.

Sometimes, you may not want to reuse session IDs. If this is the case and you understand the consequences of not reusing session IDs, use the following sample code to discard sessions and clear session ID cookies: Session. Abandon (); Response. Cookies. Add (new HttpCookie ("ASP. NET_SessionId ",""));

This code example clears the session status from the server and sets the session Status Cookie to null. A null value can effectively clear the Cookie from the browser.

When the user has not logged out of the application and the session Status times out, the application may still use the same session Status Cookie (if the browser is not closed ). This behavior will cause the user to go To the login page and provide the user's session Status Cookie. To ensure that the new ID is used when the logon page (login. aspx) is opened, empty cookies should be sent back to the client. To this end, add the Cookie to the response set. Then, send the response set back to the client. The simplest way to send empty cookies is to use the "Response. Redirect" method. Because the Cookie set always has a value for ASP. NET_SessionId, you cannot just test whether the Cookie exists. This will create a "Response. Redirect" loop. You can set query strings for redirection to the logon page.

Alternatively, you can use different cookies to notify you whether you have redirected to the logon page, as shown in the following code example. To help improve security, make sure that no user attempts to use ASP. NET Cookie and another Cookie to open the login page. The following code example uses the "FormsAuthentication" class to encrypt and decrypt the Cookie data. The code example then sets the time-out period of 5 seconds. Private void Page_Load (object sender, System. EventArgs e)
{
If (! IsPostBack &&
(Request. Cookies ["_ LOGINCOOKIE _"] = null |
Request. Cookies ["_ LOGINCOOKIE _"]. Value = ""))
{
// At this point, we do not know if the session ID that we have is a new
// Session ID or if the session ID was passed by the client.
// Update the session ID.
Session. Abandon ();
Response. Cookies. Add (new HttpCookie ("ASP. NET_SessionId ",""));
// To make sure that the client clears the session ID cookie, respond
// The client to tell
// It that we have responded. To do this, set another cookie.
AddRedirCookie ();
Response. Redirect (Request. Path );
}
// Make sure that someone is not trying to spoof.
Try
{
FormsAuthenticationTicket ticket =
FormsAuthentication. Decrypt (Request. Cookies ["_ LOGINCOOKIE _"]. Value );
If (ticket = null | ticket. Expired = true)
Throw new Exception ();
RemoveRedirCookie ();
}
Catch
{
// If someone is trying to spoof, do it again.
AddRedirCookie ();
Response. Redirect (Request. Path );
}

Response. Write ("Session. SessionID =" + Session. SessionID + "<br/> ");
Response. Write ("Cookie ASP. NET_SessionId =" + Request. Cookies ["ASP. NET_SessionId"]. Value + "<br/> ");
}

Private void RemoveRedirCookie ()
{
Response. Cookies. Add (new HttpCookie ("_ LOGINCOOKIE __",""));
}
Private void AddRedirCookie ()
{
FormsAuthenticationTicket ticket =
New FormsAuthenticationTicket (1, "Test", DateTime. Now, DateTime. Now. AddSeconds (5), false ,"");
String encryptedText = FormsAuthentication. Encrypt (ticket );
Response. Cookies. Add (new HttpCookie ("_ LOGINCOOKIE _", encryptedText ));
}



Note this sentence: Session. Abandon (); Response. Cookies. Add (new HttpCookie ("ASP. NET_SessionId ",""));
What is the difference between Session. Abandon (); and Session. clear? Session. Abandon () is actually equivalent to disconnecting the connection, while clear () is not disconnecting.
The main difference is that when Session. Abandon is used, the Session_End method is called (in InProc mode ).
The Session_Start method is triggered when the next request arrives. Session. Clear only clears all data in the Session and does not stop the Session. Therefore, it does not call those methods.

Transferred from MSDN!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.