简体   繁体   中英

when does a session get created in any asp.net web application?

Does a session get created for every page request ? even though we don't have any forms authentication enables or any session objects created in the application ?

From Microsoft Docs :

The SessionID property is used to uniquely identify a browser with session data on the server. The SessionID value is randomly generated by ASP.NET and stored in a non-expiring session cookie in the browser. The SessionID value is then sent in a cookie with each request to the ASP.NET application.

So, when a browser requests a resource which requires session state, if the Session State Module cannot find an existing session ID (either in the ASP.NET session cookie, or in the URL in the case of cookieless sessions), then a new session ID is created and returned in the session ID cookie.

The session ID is used to retrieve a set of session state values (commonly known as "session variables"). Data stored in such a "variable" will remain available as long as the session exists. If the session times out, or if the AppDomain restarts, or if the cookie becomes unavailable, then the session "variable" will contain null . Code using session state must be prepared for this:

bad code:

string user = Session["User"];
int length = user.Length;   // NullReferenceException if session was expired

better code:

string user = Session["User"];
if (user == null) {
    // Do without the user information
} else {
    int length = user.Length; // User information is available
}

Session state data is shared across all the data forms but for the sing user global data.

    Declaration For the session :
    Session["Key"] = "value";

    Session data are stored on the server side.

    Session state variables are declared when session times out.
    By default time out for session is 20 minutes.

For Example :

    **If you are using session & you are executing the first session web form & suppose you have navigated your page from web-form 1 to web-form 2.
    Then Session output will be the same.

    If suppose your o/p for web-form 1 is "2".
    Then if you have closed the browser & copy and paste the same URL to another browser.
    then you will notice that o/p will be the same Because In your URL session ID is present.
    there for it will have the same o/p.
    This is very Important to understand about session if you want to use the session in your application.**  

    ie session data session state data shared across all the web-form but only fr single user.

    For every session Unique session ID is generated.
    But is you have changed your session then new session ID is generated meaning it is only for single user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM