IHttpModule接口事件执行 获取Session 找了很多国内的都不对,从国外转过来一个测试可用的...

本文介绍了一个自定义的ASP.NET HTTP模块,通过该模块可以强制加载Session状态,确保在特定的请求处理阶段可用。文中提供了具体的实现代码,包括如何替换默认的请求处理程序以支持Session状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我的环境,asp.net4.0框架集

不多说上代码

public class MyHttpModule : IHttpModule
{
   public void Init(HttpApplication application)
   {
      application.PostAcquireRequestState += new EventHandler(Application_PostAcquireRequestState);
      application.PostMapRequestHandler += new EventHandler(Application_PostMapRequestHandler);
   }

   void Application_PostMapRequestHandler(object source, EventArgs e)
   {
      HttpApplication app = (HttpApplication)source;
//这个判断不知道干什么,注释没事,
      if (app.Context.Handler is IReadOnlySessionState || app.Context.Handler is IRequiresSessionState) {
         // no need to replace the current handler
         return;
      }

      // swap the current handler 这一样不知道为什么必须声明,反正就是注释会报错,不信你试试看
      app.Context.Handler = new MyHttpHandler(app.Context.Handler);
   }

   void Application_PostAcquireRequestState(object source, EventArgs e)
   {
      HttpApplication app = (HttpApplication)source;

//经过测试session从这里开始可以用了,我估计在下面的 MyHttpHander 里面应该也可以用,不过我没继续测试,有一些注意,这行代码下面本方法体里代码可以删掉, MyHttpHandler resourceHttpHandler
= HttpContext.Current.Handler as MyHttpHandler; if (resourceHttpHandler != null) { // set the original handler back HttpContext.Current.Handler = resourceHttpHandler.OriginalHandler; } // -> at this point session state should be available Debug.Assert(app.Session != null, "it did not work :("); } public void Dispose() { } // a temp handler used to force the SessionStateModule to load session state public class MyHttpHandler : IHttpHandler, IRequiresSessionState {
//这个类竟然必须存在,不明所以,只知道可以用
internal readonly IHttpHandler OriginalHandler; public MyHttpHandler(IHttpHandler originalHandler) { OriginalHandler = originalHandler; } public void ProcessRequest(HttpContext context) { // do not worry, ProcessRequest() will not be called, but let's be safe throw new InvalidOperationException("MyHttpHandler cannot process requests."); } public bool IsReusable { // IsReusable must be set to false since class has a member! get { return false; } } } }

 

转载于:https://www.cnblogs.com/uxinxin/p/5979853.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值