Kadir
Kadir

Reputation: 3224

Masterpage check session issue

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" %>

Upvotes: 4

Views: 10619

Answers (5)

Ravimallya
Ravimallya

Reputation: 6610

I also had similar issue faced. I used true to the Response.Redirect method so that the rest of load should gets terminated. Ref. I checked the session value in Page_Init of the master page as below.

public partial class Dashboard : System.Web.UI.MasterPage
{
    protected void Page_Init(object sender, EventArgs e)
    {
        if (Session["RoleId"] == null || Session["RoleId"].ToString() == "")
        {
            Response.Redirect("/account", true);
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
                setUserInfo();
        }
    }
}

Hope it helps.

Upvotes: 1

Kadir
Kadir

Reputation: 3224

Fix: It will solve your issue.

protected void Page_Init(object sender, EventArgs e)
{
    if (Session["master"] != null)
    { }
    else
    {
        Response.Redirect("login.aspx?link=" + System.Web.HttpContext.Current.Request.Url.PathAndQuery);
    }
}

Upvotes: 1

Jupaol
Jupaol

Reputation: 21365

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:

enter image description here

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

Alternatives:

  • Since you are checking if the user is authenticates, it would be better if you rely on the ASP.Net authentication and authorization API

Workarounds (if you insist to use your own authentication mechanism):

  • (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)

    • Application_BeginRequest.
    • Application_AuthenticateRequest.
    • Application_PostAuthenticateRequest.
    • Application_DefaultAuthentication.
    • Application_AuthorizeRequest.
    • Application_PostAuthorizeRequest.
    • Application_ResolveRequestCache.
    • Application_PostResolveRequestCache.
    • Application_MapRequestHandler. Fired only when the server is running IIS 7 in Integrated Mode and at least >Net Framework 3.0
    • Application_PostMapRequestHandler.
    • Application_AcquireRequestState.
    • Application_PostAcquireRequestState.
    • Application_PreRequestHandlerExecute.
    • The page event handler is executed. (refer to the page life cycle)
    • Application_PostRequestHandlerExecute.
    • Application_ReleaseRequestState.
    • Application_PostReleaseRequestState
    • Application_UpdateRequestCache.
    • Application_PostUpdateRequestCache
    • Application_LogRequest. Fired only when server is IIS 7 Integrated Mode and at least .Net Framework 3.0
    • Application_PostLogRequest. Fired only when server is IIS 7 Integrated Mode and at least .Net Framework 3.0
    • Application_EndRequest.

    For more info:

  • 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

Upvotes: 7

nunespascal
nunespascal

Reputation: 17724

IIS has standard methods for authentication and authorization.

If you want to restrict access to certain areas of your website if the user isn't logged in, then there are mechanisms in the configuration that allow for that:

In your web.config you can add:

<location path="LoginRequiredDir">
  <system.web>
     <authorization>
        <deny users="?"/>
     </authorization>
  </system.web>
</location>

This will automatically take users to the login page if they are not logged in.

Upvotes: 1

Akash KC
Akash KC

Reputation: 16310

You define the above code Page_Load method in following way:

 protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["user"] != null && Session["user"].ToString() != "")
        {
            //do code here
        }
        else
        {
            Response.Redirect("/Account/Login.aspx?link=" + System.Web.HttpContext.Current.Request.Url.PathAndQuery);
        }
    }

Upvotes: 0

Related Questions