[英]Maintaining session in a class C#
我正在尝试为MVC应用程序的类维护会话。 以下是我在变量中使用get和set会话的代码。 但是,每当设置后我访问此变量时,它就会给出null。
public static class MySession
{
public static string MyVar
{
get
{
return HttpContext.Current.Session["MyVar"] == null ? "" : HttpContext.Current.Session["MyVar"].ToString();
}
set
{
HttpContext.Current.Session["MyVar"] = value;
}
}
}
我曾经设置为MySession.MyVar="testData";
但是当我访问string str = MySession.MyVar;
它给出null
值。 有人知道为什么不保存我的会话吗?
会话变量非常容易为空,即每次由用户,浏览器,网络或应用程序本身创建新会话时。 这就是为什么,强烈建议使用if ... else块将其包装。
if(Session["key"] != null) {
// Variable exists for the session
// use variable
} else {
// Variable doesn't exist in the session
// create and user variable
}
但是,如果仍然总是得到null
,则应检查出了什么问题。 我敢打赌,还有一些其他代码或过程可以终止先前的会话并重新启动它们。 您应该知道您还可以以编程方式也删除所有会话,这也可能导致此问题。
此外,可以使用类使用和提供Session变量,这没有问题。 只需确保未刷新集合Session
。
我的猜测是您尚未启用会话状态。
<system.web>
<sessionState mode="InProc" timeout="60"/>
<system.web>
在MVC中,默认情况下禁用会话状态,除非绝对必要,否则通常不建议使用该状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.