I'm fixing my friend's codes. And I have a problem with session value in masterpage. I'm checking session is null or empty in masterpage and if it's null go to login page. But other pages that created by masterpage never works.
if (Session["user"] != null && Session["user"] != "")
{ }
else
{
Response.Redirect("/Account/Login.aspx?link=" + System.Web.HttpContext.Current.Request.Url.PathAndQuery);
}
I tried with Session["user"].ToString() but same result.
And the otherpages have a other controls via this session so it always give error if you are not login.
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
MaintainScrollPositionOnPostback="true" CodeFile="document.aspx.cs" Inherits="document" %>
Based on this:
But session control in back.master's page_load fire after default.aspx page_load so it gives me error the "session is null"
The root problem here is simple... You need to fully understand the ASP.Net page life-cycle
Take a quick look:
Basically your following assumption is wrong:
Then i create normal aspx page which name is default.aspx and is derived by back.master
From MSDN:
Master pages behave like child controls on a page: the master page Init event occurs before the page Init and Load events, and the master page Load event occurs after the page Init and Load events
Sadly an ASP.Net does not derive from a Master Page Why? because a Master Page is treated as a control so what really happens is that the master page is a child control of the Page
(Best recommendation) Create a custom HttpModule
and check the Session
object there. I think the event that best fits your needs is the: Application_AuthenticateRequest
. This is a full list of events you can choose from: (BTW there's no need to create a new HttpModule, you could subscribe to events using the Global.asax file of your web application, use an HttpModule only if you would like to encapsulate the logic to reuse it)
For more info:
ASP.NET Application Life Cycle Overview for IIS 5.0 and 6.0
ASP.NET Application Life Cycle Overview for IIS 7.0
Create a generic page inheriting from Page
and place the check code there in the PreLoad
or Load
event, both events would work and finally inherit all your pages from this page
(Not recommended) If you want to encapsulate the check inside the Master Page, you could use the Init
event
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