通常我們需要在每個頁面判斷Session是否存在,據此來斷定用戶是否登錄,如果沒有登錄,就跳轉到Login頁面。
如果每個頁面都去寫
if (Session["user"]==null)
{
Response.Redirect("login.aspx");
}
下面介紹一種更簡單的解決方案
asp.net頁面.cs文件都是繼承System.Web.UI.Page,鼠標指向page然后轉到定義,我們就會看到page里面所有的數據,.cs 類文件是只讀的,我們無法修改,就只能新建一個類去繼承page ,然后重寫里面的一些方法,然后再讓所有的頁面繼承這個類。
先引用 Using System.Web.UI.Page;
public class Class1:Page
{
//重寫OnInit
override protected void OnInit(EventArgs e)
{
if (System.Web.HttpContext.Current != null)
{
base.OnInit(e);
this.Error += new System.EventHandler(this.Page_Error);
}
//如果Session 不存在
if (Session["user"]==null)
{
Response.Redirect("Login.aspx");
}
}
/// <summary>
/// 錯誤處理方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Error(object sender, System.EventArgs e)
{
try
{
Exception currentError = Server.GetLastError();
string msg = "出錯頁面:" + Request.Url.ToString() + " 出錯方法:" + currentError.TargetSite.ToString() + " 錯誤信息:" + currentError.Message+" 日期"+DateTime.Now.ToString();
Common.TextOperations.WriteException(msg);
Server.ClearError();
}
catch
{
System.Web.HttpContext.Current.Response.Redirect("/Error.html");
}
}
}
}
之前頁面是這樣寫的public partial class WebForm1 : Page
現在每個頁面,繼承class1 就行了。
public partial class WebForm1 : Class1