捕获 global.asax (C#、.Net) 之外的会话状态事件



我需要使用 Session_Start(( 和 Session_End(( 捕获会话状态事件。我的项目的性质限制了更改源代码,因此我无法将这些方法添加到 global.asax 文件中。我该怎么做?我已经尝试继承 global.asax.cs 类并在那里添加了方法,但它们没有命中。

您可以使用 HTTP 模块执行此操作。下面是一个示例:

public class SessionCatchingModule : IHttpModule //You will need to import System.Web
{
    public void Init(HttpApplication context)
    {
        //Get the SessionstateModule and attach our own events to it
        var module = context.Modules["Session"] as SessionStateModule;
        if (module != null)
        {
            module.Start += this.Session_Start;
            module.End += this.Session_end;
        }
    }
    private void Session_Start(object sender, EventArgs args)
    {
        //Oh look, a session has started
    }
    private void Session_End(object sender, EventArgs args)
    {
        //Oh look, a session has ended
    }
}

现在,在您的web.config确保正在加载模块:

<system.webServer>
  <modules>
    <add name="SessionCatchingModule" 
         type="YourNamespace.Goes.Here., SessionCatchingModule" />
  </modules>
</system.webServer>

最新更新