检查每个页面的会话?

Das*_*hsa 6 .net c#

我是.NET的新手 - 我正在建立一个只有登录用户才能看到的管理部分的网站.我创建了登录代码,一旦用户通过身份验证,我就会为它们分配一个会话变量.我的问题是:是否有更有效的方法来检查会话变量而不是在每个页面上都有以下功能?

protected void Page_Load(object sender, EventArgs e)
{
      checkSession();

 }
public void checkSession()
{
    if (Session["LoggedIn"] != "true")
    {
        Response.Redirect("default.aspx");
    }
}
Run Code Online (Sandbox Code Playgroud)

谢天谢地!

ano*_*ari 5

如果您正在使用a,MasterPage您可以将检查代码放在MasterPage's Page_Load事件中,如果不使用Global.asax或自定义HttpModule并将cheking代码放在第一个AcquireRequestState事件处理程序和PostRequestHandlerExecute第二个事件处理程序中

与Global.asax一起使用

public class Global : System.Web.HttpApplication
{ ...
    void Application_AcquireRequestState(object sender, EventArgs e)
    {            
        HttpContext context = HttpContext.Current;
        // CheckSession() inlined
        if (context.Session["LoggedIn"] != "true")
        {
          context.Response.Redirect("default.aspx");
        }
    }
  ...
}
Run Code Online (Sandbox Code Playgroud)