1.新建类xx.cs:IHttpModule,继承该接口,实现接口方法
public class ValidateSessionHttpModule : IHttpModule { public void Dispose() { throw new NotImplementedException(); } /// <summary> /// 完成请求管道中事件的注册 /// </summary> /// <param name="context"></param> public void Init(HttpApplication context) { //throw new NotImplementedException(); //给事件注册方法,当事件被触发时候执行 context.AcquireRequestState += Context_AcquireRequestState; } private void Context_AcquireRequestState(object sender, EventArgs e) { //throw new NotImplementedException(); HttpApplication application = sender as HttpApplication; HttpContext context = application.Context; string url = context.Request.Url.ToString(); if (url.Contains("Admin")) { if (context.Session["key"] == null) { context.Response.Redirect("/Login.aspx"); } } } }
2.或者在Global文件的相应方法中写自己的代码
public class Global : System.Web.HttpApplication { /// <summary> /// Web应用程序第一次启动时候调用的方法,并且只被调用一次 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Application_Start(object sender, EventArgs e) { #region 定时任务框架 #endregion } /// <summary> /// 会话开始时候调用,可以用来通过Application统计总访问人数 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Session_Start(object sender, EventArgs e) { } protected void Application_BeginRequest(object sender, EventArgs e) { } protected void Application_AuthenticateRequest(object sender, EventArgs e) { } /// <summary> /// 全局的异常处理点,如果程序中有trycache则不调用该方法 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Application_Error(object sender, EventArgs e) { //获取异常信息 Exception ex = HttpContext.Current.Server.GetLastError(); //Log4Net写日志 } protected void Session_End(object sender, EventArgs e) { } protected void Application_End(object sender, EventArgs e) { } }
时间: 2024-11-03 21:20:26