第一种方法:
public partial class BasePage : System.Web.UI.Page
{
public BasePage(
{
this.Load += new EventHandler(BasePage_Load);
}
protected void BasePage_Load(object sender, EventArgs e)
{
if (Session["UserInfo"] == null)
{
Response.Redirect("~/index.html");
}
}
}
其他页面只要继承这个BasePage即可!
public partial class CheckBox : BasePage
{
protected void Page_Load(object sender, EventArgs e){}
}
---------------------------------------------------------------------------------------------------------------
或者采用这种方式: 原理是,
每次请求时都会调用托管代码模块
在Web.config中配置在Configuration节点modules下添加配置访问地点
<system.webServer>
<modules>
<add type="RichardTest.RequestHandle" name="demo"/>
<!--type是指命名空间.类名-->
</modules>
</system.webServer>
在RequestHandle中可以这么处理
public class RequestHandle :IHttpModule //需要继承此接口
{
public void Dispose()
{ }
public void Init(HttpApplication context)
{
context.AcquireRequestState += new EventHandler(CheckIsLog);
}
public void CheckIsLog(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
if (app.Context.Session != null && app.Context.Session["UserInfo"] == null && app.Context.Request.Url.ToString().IndexOf("Compare.aspx") < 0) //当登录页时无需验证,即可成功跳转
{
app.Response.Redirect("http://www.baidu.com");
}
}
}
这两种方法区别:(建议
使用第二种方法)
- 使用BasePage时需要每个页面继承,写法麻烦,且有遗漏风险
- 使用BasePage时,当页面存在Frame时,可能会在页面某个部分跳转其他页面。