gpt4 book ai didi

asp.net - 在 Application_BeginRequest 中设置 session 变量

转载 作者:行者123 更新时间:2023-12-02 02:55:34 26 4
gpt4 key购买 nike

我使用的是 ASP.NET MVC,我需要在 Application_BeginRequest 设置 session 变量。问题是,此时对象 HttpContext.Current.Session 始终为 null

protected void Application_BeginRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.Session != null)
{
//this code is never executed, current session is always null
HttpContext.Current.Session.Add("__MySessionVariable", new object());
}
}

最佳答案

尝试 Global.asax 中的 AcquireRequestState。 session 在此事件中可用,该事件针对每个请求触发:

void Application_AcquireRequestState(object sender, EventArgs e)
{
// Session is Available here
HttpContext context = HttpContext.Current;
context.Session["foo"] = "foo";
}

瓦拉马斯 - 建议编辑:

成功地将其与 MVC 3 一起使用并避免了 session 错误。

protected void Application_AcquireRequestState(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
if (context != null && context.Session != null)
{
context.Session["foo"] = "foo";
}
}

关于asp.net - 在 Application_BeginRequest 中设置 session 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5977285/

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