如何在使用ASP.NET加载页面之前检查变量并重定向到另一个页面?
我知道生命周期,而PageInit()
听起来似乎是对的,但我似乎找不到任何地方将代码放在Visual Studio中而没有错误。
我无法将onpageinit=""
放在页面声明的第一行。我想把它放在不同的地方吗?我的页面声明如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="dashboard.aspx.cs" Inherits="dashboard" MasterPageFile="~/Design.master" %>
这是我想在页面加载上运行的代码:
// 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");
}
答案 0 :(得分:2)
我建议您花时间阅读有关Asp.Net会员资格的信息。然后,如果您需要,请实现您自己的MembershipProvider
,它将处理有关验证用户请求的必要管道。
成员抽象非常有用,实现自己的提供商并不是那么困难。
也就是说,如果确实想要使用Session中的值来管理身份验证,您可以尝试将代码放在Global.asax中的Application_PostAcquireRequestState
方法中。这样,您的代码将自动被调用(几乎)所有请求到您的应用程序,它也是会话可用的第一个可用事件(据我所知)。样品:
void Application_PostAcquireRequestState(object sender, EventArgs e)
{
if (Session["LoggedUserName"] == null && !Request.Path.EndsWith("login.aspx"))
{
Response.Redirect("~/your/path/login.aspx");
}
}
答案 1 :(得分:1)
我不知道onpageinit
属性。会话变量独立于页面生命周期。会话始终可用。假设您始终使用相同的母版页,请将代码插入母版页后面的代码Pre_Init
中。
为此,请将覆盖添加到后面的代码中:
protected override void OnPreInit(EventArgs e)
{
if (session.logged_in == false)
{
Response.Redirect("login.aspx", false);
}
}
答案 2 :(得分:1)
您必须覆盖页面的OnInit方法。把它放在上面(顺序无关紧要,但我相信组织很重要)你的代码中的Page_Load事件......
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
// your code goes here
}
另外,根据您要完成的操作,我建议您查看FormsAuthentication。有了它,您可以简单地指定安全文件夹和登录页面,如果未经过身份验证,.NET会将访问者踢到登录页面。
答案 3 :(得分:-1)
您可以将此代码放在母版页中的任何位置,以检查变量并在内容页面加载之前重定向到另一个页面。
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (string.IsNullOrEmpty(Convert.ToString(Session["email"])) ||string.IsNullOrEmpty(Convert.ToString(Session["mobile"])))
{
Response.Redirect("Login.aspx");
}
}