我正在使用 C#、MVC 和 AngularJS。
我的问题是我的 MVC 程序创建了一个HttpContext.Current.Items["value"]
并在初始主控制器中设置值,但是当我的 AngularJS 通过 ajax 调用调用应用程序时,它会创建一个新会话,并且我无法获取我之前在我的家庭控制器中设置的值HttpContext.Current.Items["value"]
call.
我可以做些什么来解决这个问题吗?我想继续使用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
value 不再可用是因为您正在“在您的家庭控制器中”设置它,这是与您的 AJAX 调用完全独立的请求。
会话状态取决于 cookie,因此如果将相同的 cookie 发送回服务器,则可以检索存储在那里的数据。幸运的是,如果你们在同一个域中,AJAX会自动将cookie发送回服务器 https://stackoverflow.com/questions/2870371/why-is-jquerys-ajax-method-not-sending-my-session-cookie.
至于SessionID的变化,ASP.NET 在使用会话之前不会为其分配存储空间 https://stackoverflow.com/questions/2874078/asp-net-session-sessionid-changes-between-requests。因此,您需要在会话状态中显式存储某些内容才能实际启动会话。看这篇 MSDN 文章 https://support.microsoft.com/en-us/kb/899918了解更多信息。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)