0

I have a log in page and a content page (i.e. Home page).

If the user has not logged in, s/he will be redirected to the login page. At the login page, after the user has successfully logged in, the credential will be stored in a Session variable.

My question is, what would be the difference if I check the login status during the PreInit and Page_Load? i.e.

What is the difference between this:

protected void Page_PreInit(object sender, EventArgs e)
{
    //If the user is not logged in, redirect the user to login page
    if (Session["isLogin"] == null || Session["isLogin"] == 0)
    {
        Response.Redirect("~/Login");
    }
}

and this:

protected void Page_Load(object sender, EventArgs e)
{
    //If the user is not logged in, redirect the user to login page
    if (Session["isLogin"] == null || Session["isLogin"] == 0)
    {
        Response.Redirect("~/Login");
    }
}

Which of these is the more recommended way of implementing it? Pros and Cons?

C.J.
  • 3,409
  • 8
  • 34
  • 51
  • Have you checked it? Why don't you use the built-in [ASP.NET Membership](http://msdn.microsoft.com/en-us/library/yh26yfzy(v=vs.100).aspx)? – Tim Schmelter Jun 18 '14 at 15:12
  • In term of implementation, it doesn't look any different to me. Both work just fine. – C.J. Jun 18 '14 at 15:13
  • I did not use the ASP.NET membership because it is too redundant and most of the premade features do not meet my requirements. – C.J. Jun 18 '14 at 15:14
  • Why dont you make use of built in FormsAuthentication in asp.net? – Murali Murugesan Jun 18 '14 at 15:17
  • @Murali what do you mean? Are you referring to ASP.NET Memebership and/or Identity? If yes, like I mentioned previously, the built in features are way too redundant that it will take more effort to modify them than to create one myself – C.J. Jun 18 '14 at 15:19
  • 1
    @C.J. Check this [FormsAuthentication Explained](http://msdn.microsoft.com/en-us/library/ff647070.aspx) – Murali Murugesan Jun 18 '14 at 15:23
  • @Murali thank you for the extra info, however given the existing database and requirements, it is still hard to incorporate the FOrmAuthentication to my application. Also, it doesn't answer my question above. – C.J. Jun 18 '14 at 15:26
  • 1
    @C.J. Have a look of http://stackoverflow.com/questions/8457297/asp-net-page-life-cycle-explanation – Murali Murugesan Jun 18 '14 at 15:29

1 Answers1

1

For your purpose it's better to use the Page_PreInit event because you'll avoid to load unnecessary controls and viewstate that you're not going to use if the redirection is called.

You can find a good description of page events, what is loaded in the page and what you can control on each stage here

MarceloRB
  • 86
  • 1
  • 7