我在用ASP.NET MVC和我需要将会话变量设置为Application_BeginRequest.问题是,在这一点上,对象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中try AcquireRequestState.会话在此事件中可用,该事件 for each 请求触发:

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

Valamas - Suggested Edit:

成功地将其与MVC 3一起使用,避免了会话错误.

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

Asp.net相关问答推荐

Visual Studio发布的网站得到错误类型JObject is not defined when page is load on server"''"

在 Web.Config 中模拟标签

检测 ASP.NET 中的内存泄漏

ASP.NET @Register 与 @Reference

Web api 不支持 POST 方法

如何从 URI 中删除 PROTOCOL

在 Asp.net mvc5 中使用用户名而不是邮箱作为身份

如何在 ASP.Net Core Razor 页面上重定向

.Net Standard 2.0 类库是否有通用配置文件?

如何获取 ActionLink 的工具提示?

带有文件名的 ASP.net MVC4 WebApi 路由

MVC5 身份验证中的......与主域之间的信任关系失败

如何在我自己的方法中模仿 string.Format()?

HttpContext.Current.Request.Url.Host 它返回什么?

压力测试 ASP.Net 应用程序

如何直接在 .aspx 页面中访问 web.config 设置?

ASP.NET Excel 导出编码问题

ASP.NET 核心,更改未经授权的默认重定向

解耦 ASP.NET MVC 5 标识以允许实现分层应用程序

如何在asp.net的GridView中按列名而不是按索引获取单元格值