Session是服务端一种状态保持机制,可以将各种类型的数据存储到Session,最终这些数据是存储到服务器的内存中。
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script type="text/javascript">
window.onload = function () {
var validateCode = document.getElementById("validateCode");
validateCode.onclick = function () {
document.getElementById("imgCode").src = "ValidateImageCode.ashx?d=" + new Date().getMilliseconds();
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
用户名:<input type="text" name="txtName" value="<%=UserName%>" /><br />
密码;<input type="password" name="txtPwd" /><br />
验证码:<input type="text" name="txtCode" /><img src="ValidateImageCode.ashx" id="imgCode" /> <a href="javascript:void(0)" id="validateCode"> 看不清</a><br />
<input type="submit" value="登录" /><span style="font-size:14px;color:red"><%=Msg %></span>
</div>
</form>
</body>
</html>
public partial class UserLogin : System.Web.UI.Page
{
public string Msg { get; set; }
public string UserName { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
//string userName = Request.Form["txtName"];
//UserName = userName;
if (CheckValidateCode())//先判断验证码是否正确.
{
CheckUserInfo();
}
else
{
//验证码错误
Msg = "验证码错误!!";
}
}
}
#region 判断用户名密码是否正确
protected void CheckUserInfo()
{
//获取用户输入的用户名和密码.
string userName = Request.Form["txtName"];
UserName = userName;
string userPwd = Request.Form["txtPwd"];
//校验用户名密码.
BLL.UserInfoService UserInfoService = new BLL.UserInfoService();
string msg = string.Empty;
UserInfo userInfo = null;
//判断用户名与密码
if (UserInfoService.ValidateUserInfo(userName, userPwd, out msg, out userInfo))
{
Session["userInfo"] = userInfo;
Response.Redirect("UserInfoList.aspx");
}
else
{
Msg = msg;
}
}
#endregion
#region 判断验证码是否正确
protected bool CheckValidateCode()
{
bool isSucess = false;
if (Session["validateCode"] != null)//在使用Session时一定要校验是否为空
{
string txtCode = Request.Form["txtCode"];//获取用户输入的验证码。
string sysCode = Session["validateCode"].ToString();
if (sysCode.Equals(txtCode, StringComparison.InvariantCultureIgnoreCase))
{
isSucess = true;
Session["validateCode"] = null;
}
}
return isSucess;
}
#endregion
}