c# - HttpContext.Current.Session - NullReferenceException

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

我在 MVC 4 ASP.NET 项目的设置类中遇到了对象引用未设置为对象实例错误,它获取了我的当前 session 详细信息。每次我浏览页面时,该变量都会抛出 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

以上都不适合我。

最佳答案

        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"] 为 null 时,您将其包装到 Setting 类。如果您像这样更改代码,它应该可以工作。

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

关于c# - HttpContext.Current.Session - NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34113732/

相关文章:

c# - 在 C# 中实现 ISP 设计模式

c# - Entity Framework Core 在 sleep 状态下留下许多连接

c# - 为什么 config.Appsettings.Settings ["MySetting"].Value 在 Windows 7 中失败,但在其他版本中没有

c# - 哇,什么是 TryParse

c# - 列出一个月中的所有日期 ASP.NET C#

asp.net-mvc - Autofac:自定义 LifetimeScope

C# 枚举类型安全

asp.net-mvc - 带有ASP.NET MVC的JSON请求的401响应代码

c# - 在 Web API 中设置 "Content-Disposition"HTTP header

jquery - 显示工具提示而不是编写多个 jquery 函数的替代方法