【问题标题】:HttpContext.Current.Session - NullReferenceExceptionHttpContext.Current.Session - NullReferenceException
【发布时间】:2016-03-10 21:14:01
【问题描述】:

我在 MVC 4 ASP.NET 项目的 Settings 类中遇到了 Object Reference not set to an instance 错误,该类获取了我的当前会话详细信息。每次我浏览一个页面时,该变量都会抛出 NullReferenceException,并且无法理解为什么,因为它以前可以完美运行,没有任何问题。

namespace TracerCRM.Web
{
    public class Settings
    {
        public static Settings Current
        {
            get
            {
                Settings s = HttpContext.Current.Session["Settings"] as Settings;
                if (s == null)
                {
                    s = new Settings();
                    HttpContext.Current.Session["Settings"] = s;
                }

                return s;
            }
        }
    }
}

我尝试了以下我在研究过程中遇到的事情:

1:"HttpContext.Current.Session" vs Global.asax "this.Session"

2:Rare System.NullReferenceException show up for a HttpContext.Current.Session["courseNameAssociatedWithLoggedInUser"] that was previously populated?

3:The Session object is null in ASP.NET MVC 4 webapplication once deployed to IIS 7 (W 2008 R2)

4:Log a user off when ASP.NET MVC Session expires

5:Login Session lost sometimes when redirect to action in asp.net mvc 3

以上都不适合我。

【问题讨论】:

  • 当您说“因为它之前工作完美而没有任何问题”时,“它正在工作”部分是在将您的设置逻辑包装到 Settings 类之前?
  • 不,我不得不开始在项目中进行新的开发,DayPilot Calendar Control,从那时起,我就遇到了这个问题。
  • @Hennie 检查我的答案并告诉我是否有不清楚的地方。
  • @mybirthname,我试过了,还是一样的错误

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


【解决方案1】:
        public static Settings Current
        {
            get
            {
                if(HttpContext.Current.Session == null)
                {
                     Settings s = new Settings();
                     return s;
                }
                if (HttpContext.Current.Session["Settings"] == null)
                {
                    Settings s = new Settings();
                    HttpContext.Current.Session["Settings"] = s;
                    return s;
                }

                return (Settings)HttpContext.Current.Session["Settings"];
            }
        }

Session["Settings"] 为空时,您将其包装到 Setting 类。如果您像这样更改代码,它应该可以工作。

以后学习使用debug,这样的错误你会很快解决的!

【讨论】:

  • 使用 debug 看看当前情况下什么是 null。它是会话 null 吗? :D
  • @Hennie 立即查看。
【解决方案2】:

添加这个 Global.asax.cs

using System.Web.SessionState;

protected void Application_PostAuthorizeRequest()
{
    System.Web.HttpContext.Current.
        SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 2016-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多