2009-09-05 153 views
104

在我的web应用程序,我做这样的事情读会话变量:如果当前的ASP.NET会话为空,我应该怎么做?

if (HttpContext.Current.Session != null && HttpContext.Current.Session["MyVariable"] != null) 
{ 
    string myVariable= (string)HttpContext.Current.Session["MyVariable"]; 
} 

我明白为什么它来检查为什么HttpContext.Current.Session [“MyVariable的”]为空是很重要的(变量可能不已存储在Session中,或者会话因各种原因已被重置),但为什么我需要检查HttpContext.Current.Session是否为空?

我的理解是会话是由ASP.NET自动创建的,因此HttpContext.Current.Session不应该为null。这个假设是否正确?如果它可以为空,这是否意味着我也应该在其存储的东西之前检查:

if (HttpContext.Current.Session != null) 
{ 
    HttpContext.Current.Session["MyVariable"]="Test"; 
} 
else 
{ 
    // What should be done in this case (if session is null)? 
    // Is it possible to force the session to be created if it doesn't exist? 
} 
+0

ASP.NET的WebAPI将有diferent行为,您可以检查它的[访问会话使用的ASP.NET Web API(http://stackoverflow.com/questions/9594229/accessing-session-using -asp-net-web-api?answertab = votes#tab-top) – 2016-04-15 13:46:56

回答

135

是,会话对象可能为空,但只在某些情况下,哪个哟如果你的代码HttpApplication.AcquireRequestState事件之前运行

如果您只有页面中的代码,您将不会遇到此问题。我的大部分ASP .NET代码都使用Session而不重复检查null。然而,如果你正在开发一个IHttpModule或者在ASP .NET的细节方面存在问题,那么就需要考虑一些问题。

编辑

在回答评论:无论会话状态是可以依赖于的AcquireRequestState事件是否已经运行的请求。这是会话状态模块通过读取会话cookie并为您找到适当的会话变量集的工作。

AcquireRequestState在控制权交给你的页面之前运行。所以如果你从页面调用其他功能,包括静态类,你应该没问题。

如果您有一些类在启动期间执行初始化逻辑,例如在Application_Start事件中或通过使用静态构造函数,则会话状态可能不可用。这一切归结为是否存在当前请求并且AcquireRequestState已经运行。另外,如果客户端禁用了Cookie,Session对象仍然可用 - 但在下一个请求中,用户将返回一个新的空Session。这是因为如果客户没有一个会话状态包,则会给它一个Session状态包。如果客户端不传输会话cookie,我们无法识别客户端,因此他会一次又一次地接受新的会话。

+4

只是今天发现的一个快速更新。会话在页面构造函数中不可用!只有在Init事件或之后。 – 2012-08-19 17:12:06

+0

我刚刚遇到一个HttpContext.Current.Session == null是由母版页的Page_Load事件调用的代码。显然,这个_can_发生在页面的上下文中。如果我检查HttpContext.Current对象,大多数成员都被初始化,但是CurrentNotification和IsPostNotification会引发错误:{System.PlatformNotSupportedException}。不管是什么原因,这个问题在生产中并没有发生,它已经运行了多年。该平台是Windows Server 2003 R2 SP2,该应用程序具有目标框架.Net 3.5并在启用会话状态的IIS中运行。 – 2012-10-09 08:22:03

+0

我还发现,当IIS提供对磁盘上存在的资源文件(如样式表)的直接请求时,'HttpContext.Current.Session'可以为空以在Application_AcquireRequestState中进行编码。但是,页面本身的请求确实使会话对象可用于在那里编码。这至少在MVC.NET 4之下。 – 2016-04-25 09:36:30

2

ASP.NET Technical Articles

SUMMARY: In ASP.NET, every Web page derives from the System.Web.UI.Page class. The Page class aggregates an instance of the HttpSession object for session data. The Page class exposes different events and methods for customization. In particular, the OnInit method is used to set the initialize state of the Page object. If the request does not have the Session cookie, a new Session cookie will be issued to the requester.

编辑:

Session: A Concept for Beginners

SUMMARY: Session is created when user sends a first request to the server for any page in the web application, the application creates the Session and sends the Session ID back to the user with the response and is stored in the client machine as a small cookie. So ideally the "machine that has disabled the cookies, session information will not be stored".

15

如果你的Session实例为null,并且你在'ashx'文件中,只需实现'IRequiresSessionState'接口。

此接口没有任何成员,所以你只需要在类声明后添加接口名称(C#):

public class MyAshxClass : IHttpHandler, IRequiresSessionState 
+2

为我工作,与Uploadify上传脚本一起使用,谢谢。 – Renan 2011-02-10 15:59:54

+0

非常感谢您,我的登录类中的会话为空。当我将这段代码添加到我的ashx处理程序中时,它也开启了我的课程 – 2013-08-28 05:12:46

+0

我认为这很好地回答了问题。非常感谢。 – 2014-05-12 10:37:08

38

下面的语句是不完全准确:

"So if you are calling other functionality, including static classes, from your page, you should be fine"

我正在调用通过HttpContext.Current.Session引用会话的静态方法,它是空的。但是,我通过使用jQuery的ajax通过webservice方法调用该方法。

当我发现here你可以在方法的简单属性解决问题,或使用Web服务会话对象:

There’s a trick though, in order to access the session state within a web method, you must enable the session state management like so:

[WebMethod(EnableSession = true)]

By specifying the EnableSession value, you will now have a managed session to play with. If you don’t specify this value, you will get a null Session object, and more than likely run into null reference exceptions whilst trying to access the session object.

感谢马修更为舒适的解决方案。

只是想我会增加我的两美分。

埃德

+1

感谢埃德,Session在webmethod中显示为空 - 添加这个修复它。 +1 – fusi 2012-04-23 12:26:49

+1

那么,当你调用web服务时,你使用另一个请求而不是页面,所以这个语句仍然是正确的,IMO。 – driis 2012-10-09 11:18:51

+0

MSDN文档[这里](http://msdn.microsoft.com/en-us/library/byxd99hx%28v=vs.90%29.aspx#vbtskusingwebmethodattributeenablesession) - '默认值为false'。奇迹般有效。 – benjineer 2015-01-06 06:34:20

相关问题