Session对象的应用
生活随笔
收集整理的這篇文章主要介紹了
Session对象的应用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Session應用
可以使用于安全性相比之下較高的場合,比如后臺登錄。
在管理員登錄時,如果登錄成功,則需要給管理員創建一個Session對象。
在后臺登錄中,管理員擁有一定的操作時間,如果在這段時間不進行任何操作,為了保證安全,后臺將自動注銷,如果管理員需要再次進行操作,則需要再次登錄。
WebForm1.aspx代碼
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"><title>Session使用實例</title> </head> <body><form id="form1" runat="server"><div><asp:Button ID="Button1" runat="server" Text="登錄" onclick="Button1_Click" /><asp:Button ID="Button2" runat="server" Text="注銷" onclick="Button2_Click" Visible=false /><br /><asp:Label ID="Label1" runat="server" Text=""></asp:Label></div></form> </body> </html>WebForm1.aspx.cs代碼
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication1 {public partial class WebForm1 : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){if (Session["admin"] != null)//如果Session[“admin”]不為空{if (String.IsNullOrEmpty(Session["admin"].ToString()))//則判斷是否為空字符串{Button1.Visible = true;//顯式登錄控件Button2.Visible = false;//隱藏注銷控件//Response.Redirect("admin_login.aspx");//跳轉到登錄頁面}else{Button1.Visible = false;//隱藏登錄控件Label1.Text = "admin用戶已登錄";Button2.Visible = true;//顯式注銷控件}}}protected void Button1_Click(object sender, EventArgs e){Session["admin"] = "admin";//新增Session對象Response.Redirect("Session.aspx");//頁面跳轉}protected void Button2_Click(object sender, EventArgs e){Session.Clear();//刪除所有Session對象Response.Redirect("Session.aspx");}} }其中,Page_Load方法,判斷是否已經存在Session對象。
如果存在,說明當前用戶的權限是正常的,如果不存在Session對象,說明當前用戶的權限不正確,或者是非法用戶正在訪問頁面,可以直接跳轉到登錄頁面,提示用戶進行登錄。
運行結果
登錄之后
總結
以上是生活随笔為你收集整理的Session对象的应用的全部內容,希望文章能夠幫你解決所遇到的問題。