Search code examples
c#asp.netthismaster-pages

Reference 'this' in master page


I'm working on a new asp.NET project (.NET version 4.5 to be specific). I'm trying to create this project using best practices, but unfortunately I don't know the terminology to look up in this case - hopefully, this question will make it clear.

After creating a new project from the default template, I get the pages necessary for a login system. I now want to make it so that the entire site requires logging in before you're allowed to see any content. To do that, I simply check if your user is logged in on page load, and if not, redirect you to the login page.

Here's what I have so far - it works fine, but isn't "global".

On the individual page:

protected void Page_Load(object sender, EventArgs e)
{
    //If the user isn't logged in, make them log in
    redirectIfNotLoggedIn(this);
}

public static void redirectIfNotLoggedIn(_Default _Default)
{
    if (!_Default.User.Identity.IsAuthenticated) { _Default.Response.Redirect("~/Account/Login.aspx"); }
}

It works - if I am not logged in, it brings me to the Login.aspx page. If I am logged in, I am able to navigate the site. The issue with this code is that I would have to copy and paste it into every page. I therefore would like to place this code in the Page_Load of the Site.Master file, which would force the user to authenticate no matter what page they're trying to access. However, I can't use the 'this' context within Site.Master, which makes sense - but I don't know what the alternative is.

Am I going about this the right way? Is there a better way? How can I make the authentication requirement "global" for every page in the project?


Solution

  • In MasterPage, you can use this.Page to get the page object you are looking for.

    But consider also a different way of do it: I usually create a class MyBasePage, inheriting from System.Web.UI.Page, and put there all (or most) of the common logic shared by all pages in my web application.

    Then I create each page modifying the base class from System.Web.UI.Page to MyBasePage