. NET Learning Notes----Session state sessions

Source: Internet
Author: User
Tags http cookie session id

Session state Sessions

Session for server-side state management, after using the session, each client can save the actual data on the server, for each client's data, will generate a corresponding unique key (saved on the client). The client and server side is the key to confirm the identity of the client, usually this key is SessionID.

In general, SessionID is stored in the browser as a cookie and can be embedded in the URL of the Web page without the use of a cookie.

Second, server-side session

In either the Page object or the HttpContext object, there is a property named session, which, in a single session, refers to the same object.

Public HttpSessionState Session {get;}

The session object is an instance of the HttpSessionState class. The session is stored on the server side and is unique to each user who logs on to the site, and is not shared by other users.

HttpSessionState from the sessionstatemodule of HttpModule. During each request processing, the processing pipeline for the HttpApplication request checks whether the handler for the current request implements the interface IRequiresSessionState, if implemented, Then SessionStateModule will allocate httpsessionstate for this request. SessionStateModule is also responsible for SessionID generation, cookieless session management, retrieving session data from an external state provider, and binding data to the calling context of the request.

    • For generic handlers, the IRequiresSessionState interface is not implemented by default. So if you want to use the session in a generic handler, you can solve the problem by implementing the IRequiresSessionState interface, which is a markup interface and does not have any content defined.
    • For a page handler, you can set the EnableSessionState property of the page directive @page to true to allow the page to request write access to the session state. This is the default setting. You can also set the EnableSessionState property to ReadOnly, at which point the actual page class that is derived will implement the interface Ireadonlysessionstate, in which case the page can have read-only access to the session state.

The SessionStateModule module reads data from a specific state provider. What is actually accessed in the program code is a copy of the session data in local memory, which can cause data conflicts if other pages also access the session state synchronously. To avoid this situation, the SessionStateModule module implements a lock mechanism for the reader/writer and queues the access to the status values. a page that has write access to the session state retains the writer lock on the session until the request is terminated.

If a page request sets a reader lock, other requests that are processed concurrently in the same session will not be able to update the session state, but at least it can be read. If a page request sets a write lock for session state, all other pages are blocked, regardless of whether they want to read or write to the content. For example, if you have a two-segment program view that writes to the same session, a program must wait until another program finishes to write. In AJAX programming, it is important to note that this happens.

Here's a very interesting example:ASP. NET setting session after changing single thread execution

To create a new MVC project, add a controller as follows:

   public class Homecontroller:controller    {public        actionresult Index ()        {            //session["User"] = "Zhang San"; Pay special attention to this line of code            return View ();        }        Public ActionResult Test1 ()        {            thread.sleep ();            Return Content ("Long task Test1 completed");        }        Public ActionResult Test2 ()        {            return Content ("Short task Test2 complete");        }    }

The/home/index View code is as follows:

At the beginning, the line of index session[] is commented out and the output is as follows:

  

At first glance, it's normal. jquery Ajax is executed asynchronously by default, which is displayed first, no problem.

Below, enable the session code that is commented out, enter as follows:

  

The click button does not respond, although JQuery's Ajax has been sent out, but ASP. NET must wait until the first request is completed before the second request starts executing. This is from the Google browser request information can be seen, two requests are sent almost simultaneously, is the ASP. NET uses the session caused by the problem:

  

Special Note: only write session, ASP. NET will block the request, but as long as you have access to the writing session of the page, such as the session login with the system after the operation (until the session failure is locked, Of course only sessionid the same situation). There will be this problem. This is not the case with light reading session.

This problem requires attention when developing some of the concurrent ASP. NET features, such as the progress bar.

There is a way to solve this problem in MVC, in MVC, you can add the following features to this controller, but the controller cannot modify the session, only read.

[SessionState (System.Web.SessionState.SessionStateBehavior.ReadOnly)]

For WebForm, add the page behind the ASPX top (just load that blocking page):

Enablesessionstate= "ReadOnly"
Third, the client's SessionID

For each client of the session, it is necessary to save the identity of a session in the browser in order to distinguish between different sessions in subsequent requests, which we become sessionid.

SessionID is created by SessionStateModule, and after a new SessionID is created, SessionStateModule will trigger the Session_Start event. We can handle this event in the Global.asax.

        void Session_Start (object sender, EventArgs e)        {            //code to run at new session startup        }

If the session times out or is discarded, the next time the application is accessed, the SessionID does not change. Session SessionID can persist until the end of the browser session, even if the session state expires. That is, you always use the same session SessionID to represent multiple sessions, as long as the browser instance is the same.

The Session_End event marks the end of the session and is used to execute all the cleanup code required to terminate the session. Note, however, that only the InProc mode supports this event, that is, the event is only supported when the session data is stored in the ASP. NET worker process. For the Session_End event to be raised, there must be a session state first, which means that some data must be stored in the session state, and at least one request must be completed before the event is triggered.

        void Session_End (object sender, EventArgs e)        {            //code that runs at the end of the session.             //Note: The Session_End event is raised only when the sessionstate mode in the Web. config file is set to            //InProc. If the session mode is set to StateServer             //or SQL Server, the event is not raised.        }

InProc is the most commonly used and the default mode of ASP. The session state added to the cache is given a sliding expiration policy. The server will have a countdown, when the countdown to 0 means that the session expires. Sliding expiration indicates that it will be deleted if it is not used for a certain amount of time. Before it expires, any request is processed and the expiration time is reset to the session's expiration time.

For example, if the session expires at 20 minutes, each request will cause the event to be reset to 20 minutes before it expires.

The expired session data is automatically deleted. The status session module also contains a callback function that deletes the session. When the session data is deleted, the delete function is called automatically, and then the delete function raises the Session_End event. However, if the application does not have session management through InProc mode, the end event will never be raised.
SessionID consists of 120-bit strings that are allowed by the URL. By default, SessionID is sent to the client as a cookie, and if the expires expiration attribute of the cookie is not set, the SessionID fails when the browser is closed.

The SessionID string is sent to the browser and then returned to the server application in one of two ways:

    1. Use cookies.
    2. The modified URL.

Configuring session settings uses the cookieless attribute of the sessionstate element:

<sessionstate cookieless= "true"/>

Cookieless false indicates that a URL is used with cookie,true. If a URL is used, the path is as follows:

http://localhost:9090/website/(S (QIFJGKVMCNFU8J93KS74IEU7))/sessionid.aspx

Iv. expiration of the session

With regard to ASP. NET session management, it is important that the lifetime of the session-state object begins only when the first item is added to the memory dictionary. such as: only after executing the following code snippet, you can assume that the ASP.

session["xxx"] = "xxx";

The session dictionary usually contains the object type, and to read the data backwards, the returned value needs to be converted to a more specific type.

String data = session["XXX"]. ToString ();

When the data is saved to the session, the value is loaded into the specially crafted dictionary class contained in the HttpSessionState class. When the current processing request is completed, the contents of the dictionary are loaded into the state provider.
if the session times out or is discarded, the next time you access a stateless application, its session ID will not change, even if the session state expires, SessionID will continue until the end of the browser session. that is , the same session ID is always used to represent multiple sessions, as long as the browser instance is the same.

The Session_OnEnd event marks the end of the session and is used to execute all the cleanup code required to terminate the session. Note, however, that only the InProc mode supports this event , that is, the event is only supported when the session data is stored in the ASP. NET worker process. For the Session_OnEnd event to be raised, there must be a session state first, which means that some data must be stored in that session state, and at least one request must be completed.

V. SessionState configuration section

SessionState configuration section is mainly used to configure the session information, some nodes are as follows:

Configuration node Description
Mode

The mode value is as follows and the default is InProc.

Custom: Session state is using a custom data store to store session state information.

InProc: Session state is processing the ASP. NET worker process.

OFF: Session state is disabled.

SQL Server: Session state is using an out-of-process SQL servers database to store state information.

StateServer: Session state uses the out-of-process ASP. NET State Service to store state information.

CookieName

Specifies the name of the Cookie that stores the session identifier (which is the client's key), and the default value is "Asp.net_sessionid".

Cookieless

When a Web site uses Ajax, this property can only use UseCookies.

AutoDetect:Asp.net automatically determines that a cookie is used to transmit if the browser supports cookies, otherwise it is transmitted using a URI. Cookies are still used if the browser supports cookies, but cookies are disabled.
UseCookies: Cookies are used to retain user data regardless of whether the browser or device supports cookies.
UseDeviceProfile:ASP.NET is automatically judged according to HttpBrowserCapabilities. If the HttpBrowserCapabilities setting instructs the browser or device to support cookies, a cookie will be used; otherwise, an identifier will be used in the query string.
UseUri: Use UseUri to transmit SessionID regardless of whether the browser or device supports cookies

CustomProvider

Name of the custom session state provider

Timeout

Specifies how long a session is idle to expire. For in-process and state server mode, the timeout attribute cannot be set to a value greater than 525,600 minutes (1 years).

Compressionenabled

Whether the session outside the session is compressed and then transmitted. If it is compressed and then sent to SQL Server

Http://msdn.microsoft.com/zh-cn/library/h6bb9cz9.aspx

The StateServer session mode StateServer will present the session data in Aspnet_state.exe. Independent of the W3wp.exe/aspnet_wp.exe process. If stored in InProc, it is stored in the ASP.

Six, HttpSessionState class
Property Description
CodePage Gets or sets the character set identifier of the current session
Contents Gets a reference to the current session-state object
Cookiemode Gets a value that indicates whether the application is configured for a Cookie-free session
Count Gets the number of items in the session-state collection
Iscookieless Gets a value that indicates whether the session ID is embedded in the URL or stored in an HTTP Cookie. True if the session is embedded in the URL; otherwise, false
Isnewsession Gets a value that indicates whether the session was created with the current request. True if the session was created with the current request; otherwise, false
IsReadOnly Gets a value that indicates whether the session is read-only
IsSynchronized Gets a value that indicates whether access to a collection of session-state values is synchronous (thread-safe)
Item Gets or sets the individual session value session[]
Keys Gets the collection of keys that are stored in the session-state collection for all values
Lcid Gets or sets the locale identifier (LCID) of the current session
Mode Gets the current session state mode
SessionID Gets the unique identifier of the session
StaticObjects Gets the collection of objects declared by <object runat= "Server" scope= "Session"/> tag in ASP. Global.asax
SyncRoot Gets an object that can be used to synchronize access to a collection of session-state values
Timeout Gets and sets the allowable time (in minutes) between requests before the session-state provider terminates the session

Method:

Method Description
Abandon Cancel current session
Add Add a new item to the session-state collection
Clear Remove all keys and values from the session-state collection
CopyTo Copies a collection of session-state values into a one-dimensional array (starting at the specified index of the array)
GetEnumerator Returns an enumerator that can be used to read the variable names of all session states in the current session
Remove To delete an item in a session-state collection
RemoveAll Remove all keys and values from the session-state collection
RemoveAt Deletes the item at the specified index in the session-state collection

Once the Httpsessionstate.abandon method is called, the current session is no longer valid and a new session is started. Abandon causes the Sessionstatemodule.end event to be raised. A new Sessionstatemodule.start event is raised after the next request is sent. If you want to use Session.Abandon (), it's best to put it on a separate page.

code example:

        protected void Page_Load (object sender, EventArgs e) {session.add ("username", "admin");            Session.add ("Password", "123456");                      Response.Write (Session.count);               Output 2 Response.Write (session.iscookieless);                   The output False indicates that it is embedded in the cookie Response.Write (Session.CodePage);       Output 65001 Response.Write (session.contents["username"]);            Output username Response.Write ("<br/>");                 Response.Write (Session.cookiemode);               Usercookies Response.Write (session.isnewsession);                 True Response.Write (session.isreadonly);             False Response.Write (session.issynchronized); False foreach (String str in Session.keys) {Response.Write (str + ":" + session[str       ]); Username:admin password:123456} Response.Write ("&lT;br/> ");                       Response.Write (Session.LCID);                       2052 Response.Write (Session.mode);                  InProc Response.Write (Session.SessionID);            Udtst2kwyltquymd40alduyw Response.Write ("<br/>");        Response.Write (Session.StaticObjects.Count);                   0 Response.Write (Session.syncroot);                    Response.Write (Session.Timeout);            string[] Strarr = new String[session.count];            Session.copyto (strarr,0);    foreach (String str in Strarr) {Response.Write (str);            Output username password output A string array consisting of key} session.remove ("password");  Response.Write (Session.count);            Output 1 can see a session.removeat (0) less;  Deletes a Session object by index number Response.Write (Session.count); Output 0 can see another session.add ("One", "Liu Bei");            Session.Abandon ();            Response.Write (session["one"]);      Response.Write ("<a href= '/new.aspx ' > New page </a>"); Since the Ababdon () method is called, clicking on this page will not get to session["one"}

New.aspx Background code:

        protected void Page_Load (object sender, EventArgs e)        {            Response.Write (session["one"]); Although the value in the output cookie does not output any value        }

. NET Learning Notes----Session state sessions

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.