今天突然想起来,我一个朋友面试的时候有过这样一道题目:
做一个登录功能,如果用户三次登录错误,那么强行关闭登录界面
就试着做了一下:代码如下
前台:拖入两个TextBox ,一个Button 控件用来输入用户名、密码、及触发登录事件
<table border="0" cellspacing="0" cellpadding="0" width="100">
<tr>
<td>
用户名:
</td>
<td>
<asp:TextBox ID="txb_name" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
密 码:
</td>
<td>
<asp:TextBox ID="txb_pwd" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btn_login" runat="server" Text="登陆" OnClick="btn_login_Click" />
</td>
</tr>
</table>
后台:
1、在Page_Load事件中声明一个ViewState["login_num"] 用于记录登录次数
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["login_num"] = "";
}
}
2、在btn_login_Click事件
protected void btn_login_Click(object sender, EventArgs e)
{
//登录成功
if ((this.txb_name.Text.ToString().Trim().Equals("admin")) && (this.txb_pwd.Text.ToString().Trim().Equals("123")))
{
ViewState["login_num"] = 0;
ScriptManager.RegisterStartupScript(this, this.GetType(), "js", "alert('登陆成功!');", true);
}
else
{
//登录失败
1、如果第一次登录ViewState["login_num"]为空,count设为0
int count = 0;
if (ViewState["login_num"].ToString().Trim() != "")
{
count = Convert.ToInt32(ViewState["login_num"]);
}
else
{
count = 0;
}
//将登录次数保存在 ViewState["login_num"] 变量中
count++;
ViewState["login_num"] = count.ToString().Trim();
//强行关闭登录网页
if (count >= 3)
{
//在这里可以获取客户端的IP保存到数据库,保证客户清空当前的变量继续登录
.........................
代码省略
ScriptManager.RegisterStartupScript(this, this.GetType(), "js", "alert('对不起,您已经超过三次机会,强行关闭登录界 面!');window.opener=null;window.close();", true);
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "js", "alert('您还有" + Convert.ToInt32(3 - count) + "次登录机会');", true);
}
}
}
因为我还是asp.net的新手,有些地方肯定考虑的不是很周全,如果有什么地方有误或者不好的地方,请各位朋友多多的指教,
希望各位朋友能够提出意见
我现在非常疑惑我现在是该用什么来保存这个记录登录次数的变量呢?session总觉得过于浪费资源,而且在服务器中,请问用什么变量呢?
viewstate也有人提出不好,请大家说说