c# – 在每个页面检查会话?

前端之家收集整理的这篇文章主要介绍了c# – 在每个页面检查会话?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是.NET的新手 – 我正在建立一个只有登录用户才能看到的管理部分的网站.
我创建了登录代码,一旦用户通过身份验证,我就会为它们分配一个会话变量.
我的问题是:是否有更有效的方法来检查会话变量而不是在每个页面上都有以下功能
protected void Page_Load(object sender,EventArgs e)
{
      checkSession();

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

谢天谢地!

解决方法

如果你使用MasterPage,你可以将检查代码放在MasterPage的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");
        }
    }
  ...
}
原文链接:https://www.f2er.com/csharp/98885.html

猜你在找的C#相关文章