首页 asp.Net asp.net – 在Application_BeginRequest中设置会话变量

asp.net – 在Application_BeginRequest中设置会话变量

我使用ASP.NET MVC,我需要在Application_BeginRequest设置一个会话变量。问题是,在这一点对象HttpContext.Current.Session总是null。 protected void Application_BeginRequest(Object sender, EventArgs e){ if (HttpContext.Current.Sessi

我使用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中尝试AcquireRequestState。会话在此事件中可用,针对每个请求触发:

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

Valamas – 建议修改:

与MVC 3成功地使用它,并避免会话错误。

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

本文来自网络,不代表青岛站长网立场。转载请注明出处: https://www.0532zz.com/html/kaifa/asp-net/20200723/6944.html
上一篇
下一篇

作者: dawei

【声明】:青岛站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

为您推荐

返回顶部