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

时间:2022-02-18 01:14:05

我的环境,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; }
}
}
}