【问题标题】:Session variable throw nullreference exception [duplicate]会话变量抛出空引用异常[重复]
【发布时间】:2014-08-18 17:02:15
【问题描述】:

我有一个使用 ASP MVC4 的 Web 应用程序

我在

中设置了我的会话变量
protected void Session_Start()
    {
        Session["__UserLanguage"] = "EN";
    }

我在我的控制器上使用它

private void AddTranslation()
{
   string language = Request.Form["Language"];
   if (language != null)
   {
       Session["__UserLanguage"] = language;
   }
   else
   {
       language = Session["__UserLanguage"] as string;
   }
}

但是当我在 IIS 上发布它时它会返回

System.NullReferenceException: Object reference not set to an instance of an object.

当我尝试在我的控制器中获取它时

Session["__UserLanguage"] = language;

为什么? :'(

编辑:事实上,在我的应用程序中没有使用 Session_Start() 调试后...这怎么可能?

编辑2:添加后

<remove name="Session" />
<add name="Session" type="System.Web.SessionState.SessionStateModule" preCondition=""  />

这解决了我的问题!为什么不是由visual studio直接添加的:(

【问题讨论】:

  • 1) 是否在该生产应用程序上启用了会话? 2) 应用程序重新启动将刷新进程内会话。你的代码必须能够处理这个问题。
  • this post
  • 1)Yeap 会话状态在 IIS 中启用,超时时间为 30 分钟。 2)通常“Session_Start()”将始终将“EN”放入Session[“__UserLanguage”]!
  • 关于如何使用本站:不要在问题中添加答案,发布自我答案。
  • @HugoB。将 -resolved- 添加到磁贴不被认为是一种好的做法 - meta.stackexchange.com/questions/116101/…。如果您找到了解决方案,则可以将其发布为您自己问题的答案并将其标记为已接受。

标签: c# asp.net asp.net-mvc-4 iis session-variables


【解决方案1】:

添加后

<remove name="Session" />
<add name="Session" type="System.Web.SessionState.SessionStateModule" preCondition=""  />

这解决了我的问题!

【讨论】:

    猜你喜欢
    • 2022-09-30
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    • 2016-08-17
    • 2016-08-02
    • 1970-01-01
    • 2021-04-29
    • 2022-01-05
    相关资源
    最近更新 更多