在ASP.NET中,会话是用于存储和查询用户值的状态。它有助于识别在一段时间内来自同一浏览器的请求。它用于存储特定时间会话Session的值。默认情况下,为所有ASP.NET应用程序启用ASP.NET会话状态。
每个创建的会话都存储在SessionStateItemCollection对象中。可以使用Page对象的session属性获取当前会话值。让无涯教程看一个示例,如何在ASP.NET应用程序中创建访问会话。
在下面的示例中,将创建一个会话并存储用户电子邮件。此示例包含以下文件。
//Default.aspx
<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" 代码Behind="Default.aspx.cs" Inherits="SessionExample._Default" %> <head> <style type="text/css"> .auto-style1 { width: 100%; } .auto-style2 { width: 105px; } </style> </head> <form id="form1" runat="server"> <p>Provide Following Details</p> <table class="auto-style1"> <tr> <td class="auto-style2">Email</td> <td> <asp:TextBox ID="email" runat="server" TextMode="Email"></asp:TextBox> </td> </tr> <tr> <td class="auto-style2">Password</td> <td> <asp:TextBox ID="password" runat="server" TextMode="Password"></asp:TextBox> </td> </tr> <tr> <td class="auto-style2">?</td> <td> <asp:Button ID="login" runat="server" Text="Login" OnClick="login_Click" /> </td> </tr> </table> <br /> <asp:Label ID="Label3" runat="server"></asp:Label> <br /> <asp:Label ID="Label4" runat="server"></asp:Label> </form>
代码
//Default.aspx.cs
using System; using System.Web.UI; namespace SessionExample { public partial class _Default : Page { protected void login_Click(object sender, EventArgs e) { if (password.Text=="qwe123") { // Storing email to Session variable Session["email"] = email.Text; } // Checking Session variable is not empty if (Session["email"] != null) { // Displaying stored email Label3.Text = "This email is stored to the session."; Label4.Text = Session["email"].ToString(); } } } }
输出:
此应用程序将在用户登录时将用户电子邮件存储到Session会话。
它将显示存储的会话值、用户电子邮件。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)