C# 我应该在asp.net中声明会话变量的位置
我正在构建一个Asp.net应用程序。我需要在会话中保存哈希表 在页面加载时,我正在写作C# 我应该在asp.net中声明会话变量的位置,c#,.net,asp.net,session,session-variables,C#,.net,Asp.net,Session,Session Variables,我正在构建一个Asp.net应用程序。我需要在会话中保存哈希表 在页面加载时,我正在写作 protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { Session["AttemptCount"]=new Hashtable(); //Because of this line. } } 这里的问题是,当用户刷新页面时,会话[“AttemptCount”
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中,此会话将在用户打开网站后立即开始。我只想在用户转到特定页面时创建此会话。i、 e Login.aspx查看Global.asax,应用程序已启动(我想),会话启动也有一个应用程序。在类似的示例中的
session\u 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"];
}
}
public void doEvent(object sender, EventArgs e)
{
AttemptCount.Add("Key1", "Value1");
}
更新:
然后只需检查会话变量是否存在,如果不存在,则只需创建变量。你可以把它粘在一个房子里让东西更干净,就像这样
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"];
}
}
public void doEvent(object sender, EventArgs e)
{
AttemptCount.Add("Key1", "Value1");
}
然后你可以在你需要的任何地方调用属性AttemptCount
,就像这样
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"];
}
}
public void doEvent(object sender, EventArgs e)
{
AttemptCount.Add("Key1", "Value1");
}
首先测试它是否存在
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if(Session["AttemptCount"] == null)
{
Session["AttemptCount"]=new Hashtable(); //Because of this line.
}
}
}
虽然session\u start更好,但您只需要在一个页面上使用它,但可以为每个会话创建它。您可以在页面中创建如下属性:
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");
}
在Global.asax中,一旦用户打开网站,此会话将立即开始。我只想在用户转到特定页面时创建此会话。i、 aspxI已经更新了我的答案,您只需要通过检查null来检查它是否存在。您在哈希表中存储了什么?是用户尝试登录的次数吗?是的,我正在存储特定用户尝试登录的次数。因此,如果某个特定用户尝试登录超过15次,我可以阻止该会话。禁用会话cookie对人们来说非常容易。