有时候有些页面需要一些相同的检查功能,比如身份验证。明显使用HttpHandler是不方便的,因为不是所有的页面都需要去调用那些相同的功能。HttpModule的设计正是提供了一个灵活的方法解决这种功能重用的问题,它采用事件(观察者)的设计模式,将某些HttpHandler都需要的功能抽取出来,形成不同的观察者类型,这些观察者类型可以编译成类库形式,供多个网站共用
-----------------引用来自http://www.cnblogs.com/kissdodog/p/3567448.html
在编写后台网页或其他有登录功能的网页时,我们在使用session记录其登录状态时,有时在跳转的页面都要加上session是否有值的判断,这样非常麻烦,而且不高效,使用HttpHandle则能很好的解决该问题
步骤1:
在Common类库里添加一个CheckSessionHttpModult类
<pre name="code" class="csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Threading.Tasks;
namespace Common
{
public class CheckSessionHttpModult : IHttpModule//一定要在 web.config配置才能使用
{
public void Dispose()
{
throw new NotImplementedException();
}
public void Init(HttpApplication context)
{
context.AcquireRequestState += context_AcquireRequestState;//注册事件
}
public void context_AcquireRequestState(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;
string filePath= context.Request.Url.ToString();//要检测的目录,那么这个目录之外的都不用进行检测
if (filePath.Contains("Admin"))
{
if (context.Session["userInfo"] == null)
{
context.Response.Redirect("/Login.aspx");//---这个是根目录下得,不是admin下的
}
}
}
}
}
步骤2:
在web.config注册HttpModule
最后:
在调试的页面里,只要是请求服务器的,都要经过CheckSessionHttpModult 进行Session判断