Asp.NET Session Management

.NET Session Management

    For storing state in the current session, current and controls the current values ​​of all the variables of the user. As we all know, the network itself is a stateless environment, which means that each page is submitted to the server, and then returned to the browser, the page has been re-create, load, front page unless it has been submitted saves the state of all the controls, otherwise, the state will be lost, all of the controls will be re-created according to the default values.

    One powerful feature is the ability to automatically maintain the status Asp.Net server control (including its controls and Html) without the user having to write any code, Here I will introduce how to achieve Asp.Net state management.

    There are four types of state in Asp.Net in:

  • Control state

        The state can not be modified, you can directly access only or is disabled.

  • View state

        It refers to the status page and all of its controls. A round trip trying status sub maintained automatically by the ASP.NET framework. When the server transmits the page to read the view state. When the page is sent to the browser, it will top view of the state. View state is stored in a hidden field in the page status packet, the status is encoded as a string variable. Since the state but by the standard fields to maintain, so this technology is applicable to all browsers. 

        If no maintenance status page view, you can improve performance by disabling the page view state. In EnableViewState Page instructions of the property set to false, page view disabled state can be achieved.

        Another approach is the server-side label omitted form (<form runat = "server">), it can be avoided to maintain the view state, it is to be noted that this approach will disable all the processing and control server.

        In Web.config EnableViewState property profile <pages> section is false, the view state can disable the entire application. Machine.config or modified profile for the same machine can disable this view the status of all applications.

        The controls can also be maintained or disable view state of a control. We can be accomplished by setting Control.EnableViewState property. The genus is a Boolean type, default is true. Same page of the same nature, disable view state control also improves performance.

        Here should be noted that: only optimized for view state string, integer, boolean, array, arrays, lists and hash tables. Other .NET data types can be serialized in view state and persistence, but this leads to performance degradation, a huge state field of view.

        Thus, in this case the lower portion, the session status may be a better choice. On the other hand, the view state does not consume any server resources, it will not expire and the session will time out.

        In describing above us involves the concept of a state of the package. What is the status of the package? If the value is not associated with any controls, and the need to retain these values ​​in the interactive process, you can save these values ​​in a state treasure page. State data structure comprises a Po attribute / value pairs associated with the object data stored in a string. Valid objects types are primitive data types (such as: integer, byte, string, Boolean, etc.). StateBag implemented using class status packet, which is a (non-security type) dictionary object. As the operation may be any dictionary objects, add or delete items in the package state.

        Status packet using the same view state hidden field is maintained. ViewState keyword by setting and getting values ​​of the state of the package contents.

  • Application state

        Web application includes all Web pages, components, code, files and pictures. These contents are stored in a virtual directory or subdirectories.

        Global.asax file contains a global code of the Web application. Global.asax stored in the application virtual root directory. Including Application_Start, Application_End, Application_Error, Session_Start and Session_End event handler in the Global.asax file. When an application receives the first user request, triggering the Application_Start event. If global.asax file is edited and saved the changes, then the current all pending requests will be completed at the same time lead to Application_End, and then restart the application. This sequence ineffective to restart the application, all writes state information. And restart the application is transparent to all users, since it is only after the completion of all the waiting for a request, it occurs before accepting new requests. When a request is received, the application starts over again, then triggered another Application_Start event.

        Dictionary object can be achieved using the global information sharing within the scope of the application, each object is associated with a keyword. This is done by built-in properties HttpApplication class Application implementation. Application to access the content attribute set g, and the content of the machine and by adding code directly into the application state.

  • Session State

        When we connect to a Asp.Net Web site, in fact, it has created a session. The session is stateless Web gives the state, so that the site can identify the browser session from the same start subsequent page requests. This keeps the pages until the session timeout or the end of the session so far. (Note: The default timeout Asp.Net in 20 minutes time, the timeout time may be set)

    Asp.Net provide the following features for session state:

    1. Run Cookies disabled browsers

    2. For the identification of the session request already exists

    3. Storage of data within a range in the multi-session request to use the bell. These data can be configured to restart IIS and continued throughout the runtime environment in a multi-processor (Web garden) and multi-server (Web farm), like the stand-alone single-processor and the same environmental conditions.

    4. The excitation session events, such as the Session_End Session_Start and, in these processes, or other applications global.asax code

    5. If the session ends or times out, it will automatically release the session resources

        By default, the session state stored as part of the process Asp.Net in server memory, but can also be arranged on separate servers may also store session state is stored in a separate process or outer Asp.Net on the SQL Server database, so even Asp.Net process restart or crash, the session can continue to run.

        Asp.Net use SessionID length 120 to mark and trace session, the SessionID from the client to the server and returned from the server. The approach is used to modify the configuration of HTTP Cookie or URL depending on the application. .Net Framework defined SessionID automatically without manual programming process. SessionID by the URL-legal ASCII characters, and have

    • SessionID is globally unique, there can be two sessions with the same SessionID
    • SessionID is random, even if they know it is difficult to existing SessionID SessionID other live session

        Session state is achieved by the content attribute set HttpSessionState class. This set is a critical value (non-generic) dictionary, including all session state field objects, and these objects are programmed directly added. Use the keyword set and retrieve the session dictionary.

    Session state configuration:

        Session state configuration page, we can be controlled by the Page directive at the top of the page (you can find at the beginning of the configuration item html code of the page)

        The default state of the system is to enable session state, we can also be enabled by adding EnableSessionState attribute in the Page directive, as   

        <% @ Page Language = " C# "  AutoEventWireup = " true "  CodeBehind = " Default.aspx.cs "
            Inherits
= " WebStateStudy._Default "  EnableSessionState = " true "   %>

        Disable Session State page: 
         
            EnableSessionState  =  “ false

        Session state is set to read-only, so that it can only be read session data can not be modified         

                EnableSessionState  =  “ReadOnly”

        Note: EnableSessionState is case-sensitive, session state is disabled or set to read-only reason is to improve performance. If you do not have to use session state in a page, you can disable session state in order to get a slight performance boost, but can also save server resources.

        By default, session state is stored as part of the process Asp.Net of service in memory. However, by default mode and SessionState property Web.config configuration section, enable session state independent of the process Asp.Net storage, or stored in a separate state server, or stored in a SQL Server database. In this way, the session state can still exist in the case of Asp.Net process fails to stop or restart. In addition to sudden failure stops, Asp.Net may also be configured to process each request processing periodically restarted after a period of time or a certain amount of work, to improve reliability and stability. Session state between these restart will be preserved.

        In Web.config, configuration information contained in the session state <System.web> node, and <System.web> is included in <configuration> node. as follows:         

    < System.web >

        .
    < sessionState
        mode
= " InProc "
        cookieless
= " false "
        timeout
= " 20 "
        stateConnectionString
= " tcpip=127.0.0.1:42424 "
        sqlConnectionString
= " data source=127.0.0.1;userid=sa;password= "   />

        .

        </ System.web >

    sessionState has the following options:
  • allowCustomSqlDatabase

        True to the SQL database to store session data can be user-defined database. Default is false, then the default database ASPState, and the connection can not be set string Initial Catalog

  • mode

       All pages specified by the Web.config controlled whether to disable session state. If enabled the session state storage location of the property it is
       in the process of storing session state ((Inproc) is the fastest way, it is more suitable for a small amount of variable data. However, this method is susceptible to failure of the process, and not suitable for multi-server or stand-alone multi-processor. for these cases, you need to use StateServer or SqlServer. for failure or restart the server, SqlServer is the most robust method.

  • cookieless

        Cookie stored together with the session state SessionID, so that the server can understand the request with which the session is connected. Possible values ​​include Cookieless AutoDetect, UseCookies, UseDeviceProfile and UseUri, wherein UseCookie default value.

        When set to AutoDetect, detection requesting client supports Cookie. When set to seDeviceProfile, will be determined based on whether or not support the use of Cookie HttpBrowserCapabilities setting. If these do not support the use of Cookie or specify UseUri, the SessionID will add a value to the URL in order to achieve persistence.

  • cookieName

        The name of the cookie to store SessionID. The default value is ASP.NET_SessionId.

  • customPrivder

        Custom session state provider name.

  • regenrateExpiredSessionId

        This property is used in conjunction with non-cookie session. If true then expired SessionID will be replaced with a new label. The default value is false

  • sqlCommandTimeout

        SQL command is idle before the event was canceled in seconds. The default value is 30.

  • sqlConnectionString

        Connected to the connection string specified YuXing SQL Server instance. If you must set the mode to SqlServer it.

  • stateConnectionString

        Specify the server port and for storing the session state. It must be specified if the mode is set to StateServer.

  • State network timeout

        When the value is set to StateServer mode used for designating a prior request is canceled, TCP / IP network connectivity may be in an idle seconds. The default value is 10

  • timeout

        Specified number of minutes a session times out and is inactive before the server was abandoned. The default is 20.

  • useHostingIdentity

        If this is true then ASP.Net process ID will be simulated. The default value is true

    Session application objects:

       Further a method of passing information between sessions by static objects. Static objects declared in the global.asax file. Once the Scope attribute declaration object is set to Session, then the name of the object in the session can be accessed by the application code.

 
       Talking about this, I believe we also Asp.Net session management to understand, and more able to make good use of him later in the development environment. Here I did speak Demo for the content of the above ( click to download )


Reproduced in: https: //www.cnblogs.com/shimeng3344518/archive/2007/04/21/722333.html

Guess you like

Origin blog.csdn.net/weixin_33975951/article/details/94683082