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:
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:
From MSDN:
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
PageAlternatives:
Workarounds (if you insist to use your own authentication mechanism):
(Best recommendation) Create a custom
HttpModuleand check theSessionobject 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
Pageand place the check code there in thePreLoadorLoadevent, 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
Initevent