ASP.NET Tutorial/Sessions/Session Variables

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

A session-aware base page

   <source lang="csharp">

C# version using System; using System.Web; public class SmartSessionPage : System.Web.UI.Page {

   private const string MYKEY = "mykey";
   public string MyKey
   {
       get
       {
           return (string)Session[MYKEY];
       }
       set
       {
           Session[MYKEY] = value;
       }
   }

} VB version Imports Microsoft.VisualBasic Imports System Imports System.Web Public Class SmartSessionPage

   Inherits System.Web.UI.Page
   Private Const MYSESSIONKEY As String = "mykey"
   Public Property MyKey() As String
       Get
           Return CType(Session(MYSESSIONKEY), String)
       End Get
       Set(ByVal value As String)
           Session(MYSESSIONKEY) = value
       End Set
   End Property

End Class</source>


Look for Variables

   <source lang="csharp">

<% @ Page Language="VB" %> <html> <head>

  <title>Look for Variables</title>

</head> <body>

Look for Session and Application Variables


 <%
   Dim Book, Chapter, Publisher, Author As String
   Book = Session("Book")
   Chapter = Session("Chapter")
   Publisher = Application("Publisher")
   Author = Application("Author")
   
   If (Book = Nothing) Then
     Response.Write("Book: Unknown 
") Else Response.Write("Book: " & Book & "
") End If If (Chapter = Nothing) Then Response.Write("Chapter: Unknown
") Else Response.Write("Chapter: " & Chapter & "
") End If If (Publisher = Nothing) Then Response.Write("Publisher: Unknown
") Else Response.Write("Publisher: " & Publisher & "
") End If If (Author = Nothing) Then Response.Write("Author: Unknown
") Else Response.Write("Author: " & Author & "
") End If  %>

</body> </html></source>


Retrieve the value of an item that you have stored in Session state.

   <source lang="csharp">

<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server">

   void Page_Load()
   {
       lblMessage.Text = Session["message"].ToString();
   }

</script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">

   <title>Session Get</title>

</head> <body>

   <form id="form1" runat="server">
   <asp:Label
       id="lblMessage"
       Runat="server" />
   </form>

</body> </html></source>


Save value in text box to session and read it back (VB.net/C#)

   <source lang="csharp">

<%@Page Language="VB" %> <script runat="server">

  sub Submit_Click(Sender as Object,e as EventArgs)
     if tbName.Value <>""
        Session("Name ")=tbName.Value
        Response.Write("Hi " & Session("Name ")&"!")
     else
        Response.Write("You forgot to enter a name.")
     end if
  end sub

</script> <html> <body>

  <form runat="server">
     Please enter your name:
     <input type="text" id="tbName" runat="server"/>
     
     <asp:Button id="btSubmit" text="Submit" runat="server" OnClick="Submit_Click" />
  </form>

</body> </html> //////////////////////////// <%@ Page Language="VB" %> <script runat="server">

  sub Page_Load(Sender as Object,e as EventArgs)
     Label1.Text ="Welcome back " & Session("Name ") & "!"
  end sub

</script> <html><body>

  <form runat="server">
     <asp:Label id="Label1" runat="server"/>
  </form>

</body></html> ///////////////////////////// <%@ Page Language="C#" %> <script runat="server">

  void Page_Load(Object Sender, EventArgs e) {
     Label1.Text = "Welcome back " + Session["Name"] + "!";
  }

</script> <html><body>

  <form runat="server">
     <asp:Label id="Label1" runat="server"/>
  </form>

</body></html></source>


Save value to session object and read them back (VB.net)

   <source lang="csharp">

<%@Page Language="VB" %> <script runat="server">

  sub Page_Load(Sender as Object,e as EventArgs)
     dim strVariable as string
     Session("Name")="A "
     Session("FavoriteColor")="Blue "
     Session("EyeColor")="Brown "
     Session("AMessage")="Welcome to my world "
     Session("ASPNET")="asp.net "
     for each strVariable in Session.Contents
        Label1.Text +="" & strVariable &":" & _
        Session(strVariable)&"
" next end sub

</script> <html><body>

  <form runat="server">
     <asp:Label id="Label1" runat="server"/>
  </form>

</body></html></source>


Session counter and application counter (C#)

   <source lang="csharp">

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">

   <title>Chapter 8: Counter</title>

</head> <body>

   <form id="form1" runat="server">
       <asp:Label ID="lblSessionClicks" runat="server"></asp:Label>

<asp:Label ID="lblApplicationClicks" runat="server"></asp:Label>

<asp:Button ID="btnPost" runat="server" OnClick="btnPost_Click" Text="Post" /> 
   </form>

</body> </html> File: Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page {

   int sessionCount;
   protected void Page_Load(object sender, EventArgs e)
   {
       if (Session["Count"] == null)
       {
           sessionCount = 0;
       }
       else
       {
           sessionCount = Convert.ToInt32(Session["Count"]);
       }
   }
   protected void btnPost_Click(object sender, EventArgs e)
   {
       sessionCount++;
       Session["Count"] = sessionCount;
       lblSessionClicks.Text = "You have clicked the button " + sessionCount + " times.";
       Application.Lock();
       int applicationCount = Convert.ToInt32(Application["HitCount"]);
       applicationCount++;
       Application["HitCount"] = applicationCount;
       Application.UnLock();
       lblApplicationClicks.Text = "All users have clicked the button " + applicationCount + " times.";
   }
   

}

File: Global.asax <%@ Application Language="C#" %> <script runat="server">

   void Application_Start(object sender, EventArgs e) 
   {
       // Code that runs on application startup
       Application.Add("HitCount", 0);
   }
   
   void Application_End(object sender, EventArgs e) 
   {
       //  Code that runs on application shutdown
   }
       
   void Application_Error(object sender, EventArgs e) 
   { 
       // Code that runs when an unhandled error occurs
   }
   void Session_Start(object sender, EventArgs e) 
   {
       // Code that runs when a new session is started
   }
   void Session_End(object sender, EventArgs e) 
   {
       // Code that runs when a session ends. 
       // Note: The Session_End event is raised only when the sessionstate mode
       // is set to InProc in the Web.config file. If session mode is set to StateServer 
       // or SQLServer, the event is not raised.
   }
      

</script></source>


Session counter and application counter (VB)

   <source lang="csharp">

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">

   <title>Chapter 8: Counter</title>

</head> <body>

   <form id="form1" runat="server">
       <asp:Label ID="lblSessionClicks" runat="server"></asp:Label>

<asp:Label ID="lblApplicationClicks" runat="server"></asp:Label>

<asp:Button ID="btnPost" runat="server" Text="Post" /> 
   </form>

</body> </html> File: Default.aspx.vb Partial Class _Default

   Inherits System.Web.UI.Page
   Dim iSessionCount As Integer
   Protected Sub Page_Load(ByVal sender As Object, _
           ByVal e As System.EventArgs) Handles Me.Load
       If Session("Count") Is Nothing Then
           iSessionCount = 0
       Else
           iSessionCount = CType(Session("Count"), Integer)
       End If
   End Sub
   Protected Sub btnPost_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPost.Click
       iSessionCount += 1
       lblSessionClicks.Text = "You have clicked the button " & iSessionCount & " times."
       Application.Lock()
       Dim iApplicationCount As Integer = CType(Application("HitCount"), Integer)
       iApplicationCount += 1
       Application("HitCount") = iApplicationCount
       Application.UnLock()
       lblApplicationClicks.Text = "All users have clicked the button " & iApplicationCount & " times."
   End Sub
   Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
       Session("Count") = iSessionCount
   End Sub

End Class

File: Global.asax <%@ Application Language="VB" %> <script runat="server">

   Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
       " Code that runs on application startup
       Application.Add("HitCount", 0)
   End Sub
   
   Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
       " Code that runs on application shutdown
   End Sub
       
   Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
       " Code that runs when an unhandled error occurs
   End Sub
   Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
       " Code that runs when a new session is started
   End Sub
   Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
       " Code that runs when a session ends. 
       " Note: The Session_End event is raised only when the sessionstate mode
       " is set to InProc in the Web.config file. If session mode is set to StateServer 
       " or SQLServer, the event is not raised.
   End Sub
      

</script></source>


Setting and retrieving objects from the Session using State Service and a base page (C#)

   <source lang="csharp">

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">

   <title>Session State</title>

</head> <body>

   <form id="form1" runat="server">
       <asp:TextBox ID="TextBox1" Runat="server"></asp:TextBox>
       <asp:Button ID="Button1" Runat="server" Text="Store in Session" 
        OnClick="Button1_Click" />
       
<asp:HyperLink ID="HyperLink1" Runat="server" NavigateUrl="NextPage.aspx">Next Page</asp:HyperLink>
   </form>

</body> </html> File: Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : SmartSessionPage {

   protected void Button1_Click(object sender, EventArgs e)
   {
       string[] names = TextBox1.Text.Split(" ");
       Person p = new Person();
       p.firstName = names[0];
       p.lastName = names[1];
       Session["myperson"] = p;
   }

} File: NextPage.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="NextPage.aspx.cs" Inherits="Retrieve" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">

   <title>Untitled Page</title>

</head> <body>

   <form id="form1" runat="server">
   </form>

</body> </html> File: NextPage.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls;

[Serializable] public class Person {

  public string firstName;
  public string lastName;
  public override string ToString()
  {
     return String.Format("Person Object: {0} {1}", firstName, lastName);
  }

} public class SmartSessionPage : System.Web.UI.Page {

   private const string MYPERSON = "myperson";
   public Person MyPerson
   {
       get
       {
           return (Person)Session[MYPERSON];
       }
       set
       {
           Session[MYPERSON] = value;
       }
   }

} public partial class Retrieve : SmartSessionPage {

   protected void Page_Load(object sender, EventArgs e)
   {
       Person p = MyPerson;
       Response.Write(p); //ToString will be called!
   }

}</source>


Setting and retrieving objects from the Session using State Service and a base page (VB)

   <source lang="csharp">

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">

   <title>Session State</title>

</head> <body>

   <form id="form1" runat="server">
       <asp:TextBox ID="TextBox1" Runat="server"></asp:TextBox>
       <asp:Button ID="Button1" Runat="server" Text="Store in Session" 
        OnClick="Button1_Click" />
       
<asp:HyperLink ID="HyperLink1" Runat="server" NavigateUrl="NextPage.aspx">Next Page</asp:HyperLink>
   </form>

</body> </html> File: Default.aspx.vb

Partial Class _Default

   Inherits SmartSessionPage
   Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
       Dim names As String()
       names = TextBox1.Text.Split(" "c) " " "c creates a char
       Dim p As New Person()
       p.firstName = names(0)
       p.lastName = names(1)
       Session("myperson") = p
   End Sub

End Class File: NextPage.aspx <%@ Page Language="VB" AutoEventWireup="false" CodeFile="NextPage.aspx.vb" Inherits="Retrieve" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">

   <title>Untitled Page</title>

</head> <body>

   <form id="form1" runat="server">
   </form>

</body> </html> File: NextPage.aspx.vb Imports Microsoft.VisualBasic Imports System Imports System.Web Partial Class Retrieve

   Inherits SmartSessionPage
   Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
       Dim p As Person = MyPerson
       Response.Write(p) " ToString will be called!
   End Sub

End Class

<Serializable()> _ Public Class Person

   Public firstName As String
   Public lastName As String
   Public Overrides Function ToString() As String
       Return String.Format("Person Object: {0} {1}", firstName, lastName)
   End Function

End Class Public Class SmartSessionPage

   Inherits System.Web.UI.Page
   Private Const MYSESSIONPERSONKEY As String = "myperson"
   Public Property MyPerson() As Person
       Get
           Return CType(Session(MYSESSIONPERSONKEY), Person)
       End Get
       Set(ByVal value As Person)
           Session(MYSESSIONPERSONKEY) = value
       End Set
   End Property

End Class</source>


Sorting a DataView stored in Session state.

   <source lang="csharp">

<%@ Page Language="C#" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> <%@ Import Namespace="System.Web.Configuration" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server">

   DataView dvProducts;
   void Page_Load()
   {
       dvProducts = (DataView)Session["Products"];
       if (dvProducts == null)
       {
           string conString = WebConfigurationManager.ConnectionStrings["Products"]. ConnectionString;
           SqlDataAdapter dad = new SqlDataAdapter("SELECT Id,Title,Director FROM Products", conString);
           DataTable dtblProducts = new DataTable();
           dad.Fill(dtblProducts);
           dvProducts = new DataView(dtblProducts);
           Session["Products"] = dvProducts;
       }
   }
   protected void grdProducts_Sorting(object sender, GridViewSortEventArgs e)
   {
       dvProducts.Sort = e.SortExpression;
   }
   void Page_PreRender()
   {
       grdProducts.DataSource = dvProducts;
       grdProducts.DataBind();
   }

</script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">

   <title>Session DataView</title>

</head> <body>

    <form id="form1" runat="server">
    <asp:GridView
        id="grdProducts"
        AllowSorting="true"
        EnableViewState="false"
        OnSorting="grdProducts_Sorting"
        Runat="server" />
    
<asp:LinkButton id="lnkReload" Text="Reload Page" Runat="server" />
    </form>

</body> </html></source>


Store user defined object in Session (C#)

   <source lang="csharp">

File: Default.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="SessionStateExample" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">

   <title>Untitled Page</title>

</head> <body>

   <form id="form1" runat="server">
  <asp:Label id="lblSession" 
             runat="server" 
             Width="472px" 
             Font-Size="Medium" 
             Font-Names="Verdana" 
             Font-Bold="True"></asp:Label>
  

   <asp:ListBox id="lstItems" 
                Width="208px" 
                Height="128px" 
                runat="server"></asp:ListBox>
   <asp:Button id="cmdMoreInfo" 
               Width="120px" 
               Text="More Information" 
               runat="server" 
     OnClick="cmdMoreInfo_Click"></asp:Button>
   

<asp:Label id="lblRecord" runat="server" Width="272px" Font-Size="Small" Font-Names="Verdana" Font-Bold="True"></asp:Label>
   </form>

</body> </html>

File: Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class SessionStateExample : System.Web.UI.Page {

 protected void Page_Load(object sender, EventArgs e)
 {
   if (!this.IsPostBack)
   {
     Product piece1 = new Product("A","A Inc.", 7.9M);
     Product piece2 = new Product("B","B Inc.", 6.5M);
     Product piece3 = new Product("C","C Ltd.", 3.1M);
     Session["Product1"] = piece1;
     Session["Product2"] = piece2;
     Session["Product3"] = piece3;
     lstItems.Items.Add(piece1.Name);
     lstItems.Items.Add(piece2.Name);
     lstItems.Items.Add(piece3.Name);
   }
   lblSession.Text = "Session ID: " + Session.SessionID;
   lblSession.Text += "
Number of Objects: "; lblSession.Text += Session.Count.ToString(); lblSession.Text += "
Mode: " + Session.Mode.ToString(); lblSession.Text += "
Is Cookieless: "; lblSession.Text += Session.IsCookieless.ToString(); lblSession.Text += "
Is New: "; lblSession.Text += Session.IsNewSession.ToString(); lblSession.Text += "
Timeout (minutes): "; lblSession.Text += Session.Timeout.ToString(); } protected void cmdMoreInfo_Click(object sender, EventArgs e) { if (lstItems.SelectedIndex == -1) { lblRecord.Text = "No item selected."; } else { string key = "Product" +(lstItems.SelectedIndex + 1).ToString(); Product piece = (Product)Session[key]; lblRecord.Text = "Name: " + piece.Name; lblRecord.Text += "
Manufacturer: "; lblRecord.Text += piece.Description; lblRecord.Text += "
Cost: " + piece.Cost.ToString("c"); } }

}

class Product

{

   private string name;
   public string Name
   {
       get { return name; }
       set { name = value; }
   }
   private string description;
   public string Description
   {
       get { return description; }
       set { description = value; }
   }
   private decimal cost;
   public decimal Cost
   {
       get { return cost; }
       set { cost = value; }
   }
 public Product(string name, string description,
   decimal cost)
 {
   Name = name;
   Description = description;
   Cost = cost;
 }

}</source>


Using Session State

   <source lang="csharp">

Items stored in Session state are scoped to a particular user. You use Session state to store user preferences or other user-specific data across multiple page requests. Session state has no size limitations. Session state can represent more complex objects than simple strings of text. <%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server">

   void Page_Load()
   {
       Session["message"] = "Hello World!";
   }

</script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">

   <title>Session Set</title>

</head> <body>

   <form id="form1" runat="server">

Session item added!

   </form>

</body> </html></source>