我应该在asp.net中声明一个会话变量
我正在构建一个Asp.net应用程序。 我需要在会话中保存HashTable。
在页面加载我正在写
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { Session["AttemptCount"]=new Hashtable(); //Because of this line. } }
这里的问题是,当用户刷新页面时,会话[“AttemptCount”]也会刷新。 我想知道我应该在哪里申报
Session["AttemptCount"]=new Hashtable();
所以我的看法不会被彻底改变。
编辑在Global.asax中,只要用户打开网站,此会话就会开始。 我想仅在用户转到特定页面时才创建此会话。 即Login.aspx
在Global.asax的Session_Start
方法中执行此操作…
protected void Session_Start(object sender, EventArgs e) { Session["AttemptCount"]=new Hashtable(); }
更新:
然后只需检查会话变量是否存在,如果它不仅创建变量。 你可以把它粘在一个房产里,让事情变得更清洁……
public Hashtable AttemptCount { get { if (Session["AttemptCount"] == null) Session["AttemptCount"]=new Hashtable(); return Session["AttemptCount"]; } }
然后你可以随时随地打电话给AttemptCount
这个属性……
public void doEvent(object sender, EventArgs e) { AttemptCount.Add("Key1", "Value1"); }
你可以在你的页面中创建这样的属性:
protected Hashtable AttemptCount { get { if (Session["AttemptCount"] == null) Session["AttemptCount"] = new Hashtable(); return Session["AttemptCount"] as Hashtable; } }
然后你可以使用它而不必担心:
protected void Page_Load(object sender, EventArgs e) { this.AttemptCount.Add("key", "value"); }
测试它是否存在
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { if(Session["AttemptCount"] == null) { Session["AttemptCount"]=new Hashtable(); //Because of this line. } } }
虽然session_start更好,但您只需要在一个页面上使用它,但您可以为每个会话创建它。
Hashtable hastable_name=new Hashtable() Session["AttemptCount"]=hastable_name
看看Global.asax和Application_Started(我认为),还有一个会话也开始了。
上述就是C#学习教程:我应该在asp.net中声明一个会话变量分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1019853.html