步步为营-81-HttpModule(再谈Session)
说明:session用于记录数据信息并存放在服务器内存中,但是存在一些问题.例如当使用服务器集群是会出现session丢失等情况.虽然微软提供了一些解决方案(Session进程外存储,或者存到数据库中),但是效果不尽人意.常用的还是Memcache或者Redis等分布式缓存
在步步为营-76-用户登录(Session+Cookie)的1.4中通过封装CheckSession来实现身份校验(在请求管道的第11和第12事件中间),其实还可以通过HttpModule来实现(请求管道的第9个事件,AcquireRequestState),
1.1 创建实现IHttpModule接口的类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; namespace NewsCommon { //01 定义SessionHttpModule,实现IHttpModule接口 public class SessionHttpModule:IHttpModule { 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 = sender as HttpApplication; //获取当前的httpcontext HttpContext context = application.Context; //获取用户请求的URL地址 string url = context.Request.Url.ToString(); if (url.Contains("后台页面")) { if (context.Session["userInfo"] == null) { context.Response.Redirect("/Login.aspx"); } } } } }
1.2 配置WebConfig文件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!--配置HttpModule --> <system.webServer> <modules> <add name="SessionHttpModule" type="NewsCommon.SessionHttpModule"/> </modules> </system.webServer>
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步