HttpContext.Current.Items 无效,因为AngularJS调用创建新会话

我正在使用C#,MVC和AngularJS。

我的问题是我的MVC程序创建了一个HttpContext.Current.Items["value"]并在初始主控制器中设置了值,但是当我的AngularJS用ajax调用命中应用程序时,它会创建一个新的会话,我可以’ t获取我之前在HttpContext.Current.Items["value"]调用中设置的HttpContext.Current.Items["value"]

我有什么办法可以解决这个问题吗? 我想继续使用HttpContext.Current.Items["value"]

为什么我的AngularJS调用会创建新的sessionid? 我知道会话是新的原因是因为我使用它时它们有不同的ID:

 String strSessionId = HttpContext.Session.SessionID; 

HttpContext.Current.Items是仅用于请求缓存的字典。 一旦请求完成,其中的所有值都将超出范围。

 // Will last until the end of the current request HttpContext.Current.Items["key"] = value; // When the request is finished, the value can no longer be retrieved var value = HttpContext.Current.Items["key"]; 

HttpContext.Current.Session是一个在请求之间存储数据的字典。

 // Will be stored until the user's session expires HttpContext.Current.Session["key"] = value; // You can retrieve the value again in the next request, // until the session times out. var value = HttpContext.Current.Session["key"]; 

您的HttpRequest.Current.Items值不再可用的原因是因为您将其设置为“在您的家庭控制器中”,这是与您的AJAX调用完全不同的请求。

会话状态取决于cookie,因此如果将相同的cookie发送回服务器,则可以检索存储在那里的数据。 幸运的是,如果您在同一个域中, AJAX会自动将cookie发送回服务器 。

对于SessionID更改, ASP.NET在使用之前不会为会话分配存储空间 。 因此,您需要在会话状态中明确存储某些内容才能实际启动会话。 有关更多信息,请参阅此MSDN文章 。