This is in response to a post by Anas Ghanem – regarding doing Session checks in Page Loads, and asks for a better way to do things – in my opinion there is.

Instead of doing:

public class AdminSecuredPage : System.Web.UI.Page
{
    public AdminSecuredPage()
    {}
    protected override void OnInit(EventArgs e)
    {
        // if the user is not Admin , redirect to Login Page
        if (Session["AdminUser"] == null)
            Response.Redirect("~/login.aspx");
        // this needed to initialize its base page class
        base.OnInit(e);
    }
}

You really should be doing:

image

But, you can further extend this by inherting from a parent base page, like so:

public class BasePage : System.Web.UI.Page
{
    public void RequireRole (String Role)
    {
        if (!User.IsInRole(Role))
        {
            Response.Redirect("~/Login.aspx");
        }
    }

    public void RequireAdministrator()
    {
        RequireRole("Administrator");
    }
}

And then you do the following in the page:

public partial class _Default : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        RequireRole("Administrator");

        // OR

        RequireAdministrator();
    }
}

I think this is a much more elegant way of doing things, plus you are DRY compatible, since you only have to change one url to redirect to.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • DotNetKicks
  • DZone