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!
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");
}
}
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With