Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check session in every page?

Tags:

c#

.net

I am pretty new to .NET - I am making a site that has an admin section that should only be visible to logged in users. I have created the login code and once a user is authenticated, I then assign them a session variable. My question is : is there a more efficient way to check the session variable rather than having the following function on each page?

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

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

thanks kindly!

like image 502
Dashsa Avatar asked Mar 27 '13 15:03

Dashsa


1 Answers

if you are using a MasterPage you can put the checking code in the MasterPage's Page_Load event if not use either the Global.asax or a custom HttpModule and put the cheking code inside the the AcquireRequestState event handler for the first and the PostRequestHandlerExecute event handler for the second

Exmaple with 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");
        }
    }
  ...
}
like image 144
anouar.bagari Avatar answered Sep 21 '22 01:09

anouar.bagari