Redirect in Master Page Before Content Page Load
asp.net, events, master-pages, redirect
Solution
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
...
If Access_Level > User_Level_ID Then
Response.Redirect("~/login.aspx", True)
End If
End Sub
Using Response.Redirect("~/login.aspx", True) will terminate the current page processing & redirect to desired page.
Though it is recommended to use "Response.Redirect("~/login.aspx", False)" but this will not terminate page execution. It will redirect after current page processing end.
Problem
I have code in my ASP.NET master Page_Init event page that checks if a user is authorized to be on the content page, and if not redirects them to the login page. This code works fine as far as the check itself. However, I have discovered that the content Page_Load event still fires after the above redirect. This is causing a problem on pages that assume the user is logged in and certain variables are set. This is the master page code (simplified) ``` Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init ... If Access_Level > User_Level_ID Then Response.Redirect("~/login.aspx", False) End If End Sub ``` The above test works fine, and the redirect line is executed, but doesn't take effect before the code below is fired and executes. This is the content page code ``` Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim Rec_IDs As New List(Of String) Rec_IDs = Session("Rec_IDs") lblCount.Text = String.Format("You have {0} records in your cart", CType(Rec_IDs.Count, String)) 'this gives an error if Session("Rec_IDs") is null End Sub ``` I realize I can put code in each of my content pages to check if a user is logged in / authorized, but I wanted to control it all from one location if possible. Am I doing something wrong? I've read so many pages that say the master page is the place to do the check. Thanks. :-)