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

Catching session state events outside of global.asax (C#, .Net)?

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

您可以使用 HTTP Module 来做到这一点。这是一个例子:

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>