对于我们开发的网站,总是需要登录才能访问,有的时候我们总是在每一个页面加载的时候,去判断这个用户是否登录,如果没有登录就让他跳转到登录页去登录这样比较麻烦,还不容易维护,如果我们只有一个入口去做这个判断工作,那么我们就不用每个页面去判断是否登录的逻辑了。对于大师级别的人物可以飘过了,哈哈。
于是想到了Asp.Net生命周期的管道事件-IhttpModule,在客户端发送请求的时候,是先要通过ASP.NET的管道事件的,如果在这个地方进行验证不就很好吗,如果不通过验证就直接转向登录页。
既然想好了,我们就动手来实现吧,今天我就拿一个具有框架集的后台来实现。框架集的结构如下,
<frameset rows="60,*" cols="*" frameborder="no" border="0" framespacing="0"> <frame src="top.aspx" name="topFrame" scrolling="no"> <frameset cols="180,*" name="btFrame" frameborder="NO" border="0" framespacing="0"> <frame src="menu.aspx" noresize name="menu" scrolling="yes"> <frame src="main.aspx" noresize name="main" scrolling="yes"> </frameset> </frameset> <noframes> <body>your web explorer can not user frameset!</body> </noframes>
第一步:我们首先建立一个类用CheckUserLoginModule.CS,代码如下:
public class CheckUserLoginModule : IHttpModule { public void Init(HttpApplication context) { context.PreRequestHandlerExecute += process; }
1 private static void process(Object source, EventArgs args) 2 { 3 4 HttpApplication application = (HttpApplication)source; 5 6 HttpContext context = application.Context; 7 const string LoginPageFileName = "Login.aspx"; 8 string extensionName = Path.GetExtension(context.Request.Url.LocalPath); 9 10 if (extensionName == ".aspx") 11 { 12 string currentFileName = Path.GetFileName(context.Request.Url.LocalPath); 13 if (currentFileName == LoginPageFileName) 14 { 15 return; 16 } 17 if (string.IsNullOrEmpty(context.Request.Cookies["UserID"].ToString())) 18 { 19 //这里可以根据自己的实现网站结构来进行编程 20 context.Response.Write("<script> window.parent.location.href='Login.aspx'; </script>"); 21 context.Response.End(); 22 return; 23 } 24 } 25 return; 26 }
说明:
(1)上面我在代码中已经注释了,可以你的网站结构不一样,怎么样让他跳转到登录页,需要你自己编写了。
(2)有的可能是需要Session进行编程的,这样对于PreRequestHandlerExecute这个管道事件不合适,因为在这个事件中Session是失效状态,你可以看一下管道事件在哪个事件Session是有效的,建议用PreRequestHandlerExecute就可以。
第二步:我们的管道事件编写好,怎么样才能让我们Asp.Net程序发现它,并在运行时加载它呢==注册管道事件
在Web.Config中注册这个管道事件
<httpModules>
<add name="CheckUserLoginModule" type="命名空间.CheckUserLoginModule"/>
</httpModules>
好了,这样就完成了。如果大家对ASP.net管道事件感兴趣,可以去网上找些资料,有的网友写的很是不错。了解管道事件对你的开发工作还是很有帮助的,本节代码虽少,但解决了很多实际问题。大师可以飘过
欢迎转载,请注原创地址 http://www.cnblogs.com/yxhblog/archive/2012/08/01/2618348.html