引用此answer regarding regenerating new SessionID
我在 Global.asax.cs 中创建了此代码:
protected void Application_Start(object sender, EventArgs e)
{
Bootstrapper.Initialized += new EventHandler<ExecutedEventArgs>(Bootstrapper_Initialized);
}
void Bootstrapper_Initialized(object sender, Telerik.Sitefinity.Data.ExecutedEventArgs e)
{
if (e.CommandName == "Bootstrapped")
{
EventHub.Subscribe<ILoginCompletedEvent>(LoginCompletedEventVerification);
}
}
private void LoginCompletedEventVerification(ILoginCompletedEvent evt)
{
if (evt.LoginResult == UserLoggingReason.Success)
{
var manager = new SessionIDManager();
var oldId = manager.GetSessionID(Context);
var newId = manager.CreateSessionID(Context);
bool isAdd = false, isRedir = false;
manager.SaveSessionID(Context, newId, out isRedir, out isAdd);
var ctx = HttpContext.Current.ApplicationInstance;
var mods = ctx.Modules;
var ssm = (SessionStateModule)mods.Get("Session");
var fields = ssm.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
SessionStateStoreData rqItem = null;
SessionStateStoreProviderBase store = null;
FieldInfo rqIdField = null, rqLockIdField = null, rqStateNotFoundField = null;
foreach (var field in fields)
{
if (field.Name.Equals("_store")) store = (SessionStateStoreProviderBase)field.GetValue(ssm);
if (field.Name.Equals("_rqId")) rqIdField = field;
if (field.Name.Equals("_rqLockId")) rqLockIdField = field;
if (field.Name.Equals("_rqSessionStateNotFound")) rqStateNotFoundField = field;
if ((field.Name.Equals("_rqItem")))
{
rqItem = (SessionStateStoreData)field.GetValue(ssm);
}
}
var lockId = rqLockIdField.GetValue(ssm);
if ((lockId != null) && (oldId != null))
{
store.ReleaseItemExclusive(Context, oldId, lockId);
store.RemoveItem(Context, oldId, lockId, rqItem);
}
rqStateNotFoundField.SetValue(ssm, true);
rqIdField.SetValue(ssm, newId);
}
}
请记住,我正在 Sitefinity Web 应用程序中进行开发。
每次我的应用程序在成功登录期间点击 LoginCompletedEventVerification 时,Context
都会显示为 null。现在,我最初想将此代码段添加到 Sitefinity LoginWidget 中,但实现这一目标完全是另一回事。
我没有将其包含在代码示例中,但我确实触发了 Session_Start
来创建我的应用程序的“购物车”。我只是想在身份验证后为购物车创建一个新的 SessionID。
在此事件期间我无法获取 Context
的值是否有原因?
提前致谢。我感谢任何建议或批评!
编辑: Sitefinity knowledge base article where I got my Bootstrapper_Initialized code
最佳答案
I did not include it in the code sample, but I do have Session_Start firing to create my application's "shopping cart." I am just trying to create a new SessionID for the cart after authentication.
不哦。忘记在 Application_Start
事件中访问 HttpContext。
或者,您可以在 Application_BeginRequest
中执行此操作:
private static object syncRoot = new object();
private static bool initialized = false;
public void Application_BeginRequest(object sender, EventArgs e)
{
if (!initialized)
{
lock (syncRoot)
{
if (!initialized)
{
// Do your stuff here with HttpContext
initialized = true;
}
}
}
}
您应该注意的另一件事是,HttpContext 在您可能已生成且 HTTP 请求已完成执行的任何后台线程中不可用。因此,在尝试访问此 HttpContext 时应格外小心。
关于c# - Global.asax 中的 HttpApplication.Context null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34532605/