我应该在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(我认为),还有一个会话也开始了。