我正在编写自定义IHttpModule。我需要管理HttpContext会话对象。为了启用它,我添加了从IRequiresSessionState继承的自定义IHttpHandler。然后我可以访问会话(它不是null)。我在处理程序执行后在PreRequestHandlerExecute中编写逻辑,以使会话可以访问。
然后我遇到了问题。当我向会话添加一些未保存/存储的内容时。对于我的模块中的每个连续请求,我找不到已添加到会话中的对象。
是否可以从自定义模块持久写入会话,或者我遗漏了什么?
已编辑 - > R.Isajev:
public class CustomFederationModule : IHttpModule
{
public void Dispose()
{
// TODO
}
public void Init(HttpApplication context)
{
context.PostAcquireRequestState += Application_PostAcquireRequestState;
context.PostMapRequestHandler += Application_PostMapRequestHandler;
context.PreRequestHandlerExecute += Application_PreRequestHandlerExecute;
context.BeginRequest += OnBeginRequest;
context.EndRequest += OnEndRequest;
context.Error += OnErrorOccured;
}
private void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
System.Diagnostics.Trace.WriteLine("Session ID : " + HttpContext.Current.Session.SessionID);
if (HttpContext.Current.Session["Isajev"] == null)
HttpContext.Current.Session["Isajev"] = "Rastko Isajev";
}
private void OnEndRequest(object sender, System.EventArgs e)
{
if (sender is HttpApplication)
{
HttpResponse response = (sender as HttpApplication).Response;
int statusCode = response.StatusCode;
}
}
private void OnBeginRequest(object sender, System.EventArgs e)
{
}
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 :(");
}
private void OnErrorOccured(object sender, System.EventArgs e)
{
throw new Exception("Error occured ! \n" + e.ToString());
}
// 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; }
}
}
}
在自定义模块中,我使用自定义处理程序来启用模块中的会话使用,因为它最初是无会话的。在此示例中,“Isajev”在首次调用会话时添加。在来自同一用户和浏览器的下一个呼叫中,它不在会话中。
此致 Rastko