C# 从HTTPModule访问会话变量
如何从C# 从HTTPModule访问会话变量,c#,asp.net,httpmodule,C#,Asp.net,Httpmodule,如何从HttpModule访问会话变量 我在.cs页面中设置了以下会话变量,我希望在HttpModule中访问该变量: 会话[“用户名”]=“废话” 以下是在HttpModule中使用会话的示例,可以找到: 我建议采用侵入性较小的方法。 只需使用SetSessionStateBehavior()强制ASP.NET运行时向您的模块公开会话即可(iRequestSessionState的实现仅适用于iHttpHandler) OriginalHandler.ProcessRequest(上下文)在P
HttpModule
访问会话变量
我在.cs页面中设置了以下会话变量,我希望在HttpModule
中访问该变量:
会话[“用户名”]=“废话”
以下是在HttpModule中使用会话的示例,可以找到:
我建议采用侵入性较小的方法。 只需使用SetSessionStateBehavior()强制ASP.NET运行时向您的模块公开会话即可(iRequestSessionState的实现仅适用于iHttpHandler)
OriginalHandler.ProcessRequest(上下文)
在ProcessRequest
中,如果您的代码确实调用了ProcessRequest()
有人知道这是否仍然有效吗?我在debug.assert中收到错误,说会话在此上下文中不可用。
using System;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Diagnostics;
// This code demonstrates how to make session state available in HttpModule,
// regradless of requested resource.
// author: Tomasz Jastrzebski
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;
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; }
}
}
}
public void Init(HttpApplication httpApp)
{
//SESSION WILL BE AVAILABLE IN ALL EVENTS FROM PreRequestHandlerExecute TO PostRequestHandlerExecute
httpApp.PostRequestHandlerExecute += OnPostRequestHandlerExecute;
//THIS IS THE IMPORTANT LINE
httpApp.Context.SetSessionStateBehavior(SessionStateBehavior.ReadOnly);
}