asp. net session usage and expiration instance code

  • 2020-06-19 10:05:34
  • OfStack

1.Session is one of the commonly used states in an Web session.

Session provides a way to store information in server memory. It can store any data type, including custom objects.

3. Seesion is stored separately for each client.

4. Session information is saved throughout the session as long as cookie of SessionID is not lost.

5.Session is not accessible across processes and can only be accessed by users of the session. The id identity that should be used to extract Session data is stored as Cookie in the visitor's browser cache.

6. When the session terminates, or expires, the server clears the Session object.

7.Session is often used to save ID for logged-in users.

8.Session holds data that is global across pages.

For example, we want to know how many pages are visited by users of our website. We may add to each page that users may visit:


<%
If Session("PageViewed") = ""Then
 Session("PageViewed") = 1
Else
 Session("PageViewed") = Session("PageViewed") + 1
End If
%> 

Let the user know how many pages they have visited:



<%
Response.Write("You have viewed " & Session("PageViewed") & " pages")
%>

The use of Session


<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        function getSessionClick(action) {   // This function is just to figure out where 1 Five submit buttons are clicked 
            $("#hidlgc").val("");  // Clear hidden values 
            $("#hidlgc").val(action);   // Assigns a value to a hidden control 
        }
    </script>
</head>
<body>
    <form id="form1" method="post" action="MySession.aspx">
         <table>
            <tr>
                <td> Account: </td><td><input type="text" name="txtUid" /></td>`
            </tr>
             <tr>
                <td> Password: </td><td><input type="password" name="txtPwd" /></td>
             </tr>
             <tr>                
                <td colspan="2">
                    <input type="hidden" value="" id="hidlgc" name="hidlgclick" />  
                    <input onclick="getSessionClick('lgclick')" type="submit" value=" The login " />
                    <input type="submit" onclick="getSessionClick('getSession')" value=" To obtain session" />
                    <input type="submit" onclick="getSessionClick('backLg')" value=" Log out " />
                </td>
             </tr>
         </table>
    </form>
</body>

. net code


protected void Page_Load(object sender, EventArgs e)
        {
            // The user id write session In the 
            if (Request.Form["hidlgclick"] == "lgclick")
            {
                if(Request.Form["txtUid"].ToString()=="admin"&&Request.Form["txtUid"].ToString()=="admin") // Determine user login 
                {
                    Session["userName"] = Request.Form["txtUid"].ToString();  // The user id Save to session In the 
                    Response.Write(Session["userName"].ToString()+"--- Click login "); // To obtain session , and write to the page 
                }
            }
            // To obtain Session
            if (Request.Form["hidlgclick"] == "getSession")
            {
                if (Session["userName"] != null)
                {
                    Response.Write(Session["userName"].ToString() + "--- Click on the get session"); // To obtain session , and write to the page 
                }
            }
            // Cancelling the current session is equivalent to logging out (logging out). 
            if (Request.Form["hidlgclick"] == "backLg")
            {
                Session.Abandon();
            }
        }

So how do we tell if session is expired

Method 1: The dumbest method, judged in the page_load () method on each page.



If(Session[ " UserId " ]!=null)
{
// Login success 
}
Else
{
//response.write( " <script>alter( 'please login ');</script> " );
}

This approach requires writing duplicate code on each page. Code redundancy

Method 2: You can determine in HttpModule and register in HttpModule the AcquireRequestState of the request pipeline

Event (the event to which session is available)

Steps:

1: Create a new class Module that inherits the IHttpModule interface

2: Let the Module class implement interface members.

3: Register Context in the Init() method the AcquireRequestState event (where Session is available)

4: Write in the method


void context_AcquireRequestState(object sender, EventArgs e)
    {
        HttpApplication app = (HttpApplication)sender;
        if (app.Context.Session["userId"] == null)
        {
            app.Response.Write("<script>alert(' Not logged in ');</script>");
        }
}

5: In the ES92en.config configuration file < system.web > Add 1 node under the node

<httpModules>
      <add name="demo" type="Module"/> <!--type This is followed by the namespace . The name of the class -->
    </httpModules>

Using this method, module is checked first as each page loads.

The principle is that the classes that implement the IHttpModule interface execute before the page. Disable Session before the page_load() event is executed.

This method is more efficient because it can be handled directly if session does not exist. The following series 1 events are not executed.


Method 3: Do something with the page class

The virtual method OnInit() is in the Page class.

Steps:

1: Create a class TestSession that integrates the Page class

2: Override the method OnInit() in TestSession.

3. Session was judged in OnInit() method

4: Integrate TestSession instead of inheriting Page on pages where session needs to be judged

This method is more flexible, it can inherit TestSession in the page that needs to judge session, it doesn't need to judge session's page to inherit Page directly


Session's functional defects

At present, developers of ASP are using the powerful functions of Session 1, but they found the following defects in the process of using ASP Session:

Process dependencies: ASP Session state exists in the process of IIS, the program inetinfo.exe. So when the ES160en.exe process crashes, this information is lost. In addition, restarting or shutting down the IIS service results in loss of information.
Limitations in the scope of Session state usage: when a user visits from one site to another, the Session information does not migrate to that site. For example, there may be more than one WWW server on Sina website. After a user logs in, he/she has to browse various channels, but each channel is on a different server. What if he/she wants to share Session information on these WWW servers?
Cookie dependencies: The client's Session information is actually stored in Cookie, and if the client completely disables the Cookie functionality, he will not be able to enjoy the functionality provided by Session.
In view of the above defects of ASP Session, Microsoft designers made corresponding improvements in the design and development of ES178en.ES179en Session, completely overcoming the above defects and making ES181en.NET Session a more powerful function.


Related articles: