How can I check a variable and redirect to another page before the page loads using ASP.NET?
I'm aware of the life cycle, and PageInit()
sounds like it would be right, but I can't seem to find anywhere to put the code without and error within Visual Studio.
I can't put the onpageinit=""
within the first line of my page declaration. Am I suppose to put it somewhere different? My page declaration looks like:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="dashboard.aspx.cs" Inherits="dashboard" MasterPageFile="~/Design.master" %>
This is the code that I want to run on the page load:
// Check if the user is logged in, if not send them to the login page
if (session.logged_in == false)
{
// Redirect the user to the login page
Response.Redirect("login.aspx");
}
You have to override the OnInit method of the page. Place this just above (order doesn't matter, but I believe organization is important) your Page_Load event in your code behind...
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
// your code goes here
}
Also, depending on what you are trying to accomplish, I would suggest looking into FormsAuthentication. With that you can simply specify secure folders and a login page and .NET handles kicking the visitor to the login page if they are not authenticated.