gpt4 book ai didi

c# - HttpContext.Current.Session - NullReferenceException

转载 作者:行者123 更新时间:2023-11-30 19:15:44 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com