gpt4 book ai didi

asp.net - 我可以从 HTTPModule 访问 session 状态吗?

转载 作者:行者123 更新时间:2023-12-02 06:45:54 25 4
gpt4 key购买 nike

我确实可以从我的 HTTPModule 中更新用户的 session 变量,但据我所知,这是不可能的。

更新:我的代码当前正在 OnBeginRequest () 事件处理程序内运行。

更新:根据迄今为止收到的建议,我尝试将其添加到我的 HTTPModule 中的 Init () 例程中:

AddHandler context.PreRequestHandlerExecute, AddressOf OnPreRequestHandlerExecute

但是在我的 OnPreRequestHandlerExecute 例程中, session 状态仍然不可用!

谢谢,如果我遗漏了什么,请道歉!

最佳答案

ASP.NET forums上找到了这个:

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,
// regardless 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; }
}
}
}

关于asp.net - 我可以从 HTTPModule 访问 session 状态吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/276355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com