【问题标题】:HttpContext.Current.Session throwing Object reference error in server not in localHttpContext.Current.Session 在服务器中抛出对象引用错误,不在本地
【发布时间】:2015-12-11 03:14:40
【问题描述】:

在 Authorizaiton 类中,我将用户对象分配给会话

 HttpContext.Current.Session[Constants.SessionActiveUserInfo] = userInfo;

它在本地运行良好,但在服务器上它正在抛出

“对象引用未设置为对象的实例。”

当我使用控制器/操作方法名称点击 url 时,由于会话,它会抛出 HTTP 错误 500(“对象引用未设置为对象的实例。”)。 然后,如果我再次点击 url,它就可以正常工作了。

为什么会这样?有什么帮助吗?

【问题讨论】:

  • 什么是Constants.SessionActiveUserInfo
  • 从常量类中获取会话名称

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


【解决方案1】:

我在模型视图控制器中遇到了一个问题,其中会话未实例化。我相信您遇到的问题是,当您导航到该控制器时,会话实际上并不驻留在服务器上。

下面,我不会直接调用Session,我会调用SessionModify<Example>("Sample", example);,如果存在,将赋值,如果不存在则添加Session。

我创建了一个类来帮助管理 Session:

public static class Storage
{
     public static void SessionAdd<T>(string label, T value)
     {
          if(!string.IsNullOrEmpty(label))
               HttpContext.Current.Session.Add(label, value);
     }

     public static void SessionModify<T>(string label, T value)
     {
          if(HttpContext.Current.Session[label] != null)
          {
               HttpContext.Current.Session[label] = value;
               return;
          }

          SessionAdd(label, value);              
     }

     public static T SessionModifyAndReturn<T>(string label, T value) where T : class, new()
     {
          var content = new  T();
          if(HttpContext.Current.Session[label] != null)
               HttpContext.Current.Session[label] = value;
          else { SessionAdd(label, value); }

          content = value;
          return content;
     }           
}

【讨论】:

  • 谢谢。让我实现同样的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-11
  • 2020-12-02
  • 1970-01-01
  • 2017-06-26
  • 1970-01-01
  • 2017-04-29
  • 2021-04-12
相关资源
最近更新 更多