繁体   English   中英

HttpContext.Current.Session - NullReferenceException

[英]HttpContext.Current.Session - NullReferenceException

我一直在体验一个对象引用未设置为我的MVC 4 ASP.NET项目的Settings类中的对象错误的实例 ,它获取我的当前会话详细信息。 每次我浏览页面时,变量都会抛出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: 罕见的System.NullReferenceException显示以前填充的HttpContext.Current.Session [“courseNameAssociatedWithLoggedInUser”]?

3: 部署到IIS 7后,ASP.NET MVC 4 Web应用程序中的Session对象为空(W 2008 R2)

4: 在ASP.NET MVC会话到期时关闭用户

5: 在asp.net mvc 3中重定向到操作时,登录会话有时会丢失

以上都不适合我。

        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"];
            }
        }

当它为null时,您将Session["Settings"]包装到Setting类。 如果您更改这样的代码它应该工作。

学会将来使用调试,你会很快解决这样的错误!

添加此Global.asax.cs

using System.Web.SessionState;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM