HttpContext.Current.Session - NullReferenceException

时间:2015-12-06 03:37:21

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

我在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: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

以上都不适合我。

2 个答案:

答案 0 :(得分:7)

        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类。如果您更改这样的代码它应该工作。

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

答案 1 :(得分:1)

添加此Global.asax.cs

using System.Web.SessionState;

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