Session是服务端一种状态保持机制,可以将各种类型数据存储到Session,最终这些数据是存储到服务端器的内存中。
SessionDemo.aspx
<input type="text" name="txtName" /><br />
<input type="submit" value="提交" />
SessionDemo.aspx.cs
if (IsPostBack)
{
string name = Request.Form["txtName"];
Session["userName"] = name;
// Session.Timeout = 30;
Response.Redirect("Test.aspx");
}
当给Session赋值,那么会存储到服务器的内存中(因为Session是服务端状态保持机制)。在内存中存储数据时,服务器会开辟Session的存储区域,这个区域再分响应的存储单元,并且每个单元加上一个编号,这个编号叫SessionID。
当执行到Response.Redirect时,这时服务器会向浏览器返回一个302和Location,这时SessionID会以Cookie的形式返回给浏览器,存储在浏览器的内存中。
Session默认的过期时间是20分钟,过期时间为滑动过期时间。
Test.aspx.cs
if (Session["userName"] != null)
{
Response.Write(Session["userName"].ToString());
}
else
{
Response.Redirect("Login.aspx");
}
【例子】
UserLogin.aspx
<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" /><br />
密码:<input type="text" 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>
UserLogin.aspx.cs
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
}
ValidateImageCode.ashx.cs
/// <summary>
/// ValidateImageCode 的摘要说明
/// </summary>
public class ValidateImageCode : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
//在一般处理程序中如果要使用Session必须实现.IRequiresSessionState接口.
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
Common.ValidateCode validateCode = new Common.ValidateCode();
string code = validateCode.CreateValidateCode(4);
context.Session["validateCode"] = code;
validateCode.CreateValidateGraphic(code, context);
}
}
CheckSession.cs
namespace ZWH.ItcastProject.Common
{
public class CheckSession : System.Web.UI.Page
{
//Init事件:aspx初始化时触发.
public void Page_Init(object sender, EventArgs e)
{
if (Session["userInfo"] == null)
{
Response.Redirect("UserLogin.aspx");
}
}
}
}
UserInfoList.aspx.cs
public partial class UserInfoList : Common.CheckSession
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
ZWH.ItcastProject.BLL
UserInfoService.cs
/// <summary>
/// 完成用户登录
/// </summary>
/// <param name="userName">用户名</param>
/// <param name="userPwd">用户密码</param>
/// <param name="msg">登录信息</param>
/// <param name="userInfo">登录用户信息</param>
/// <returns></returns>
public bool ValidateUserInfo(string userName, string userPwd, out string msg, out UserInfo userInfo)
{
userInfo = userInfoDal.GetUserInfo(userName);
if (userInfo != null)
{
if (userInfo.UserPass == userPwd)
{
msg = "登录成功!!";
return true;
}
else
{
msg = "用户名或密码错误!!";
return false;
}
}
else
{
msg = "没有此用户!!";
return false;
}
}
ZWH.ItcastProject.DAL
UserInfoDal.cs
public UserInfo GetUserInfo(int id)
{
string sql = "select * from userInfo where ID=@ID";
SqlParameter[] pars =
{
new SqlParameter("@ID",SqlDbType.Int)
};
pars[0].Value = id;
DataTable da = SqlHelper.GetDataTable(sql, CommandType.Text, pars);
UserInfo userInfo = null;
if (da.Rows.Count > 0)
{
userInfo = new UserInfo();
LoadEntity(userInfo, da.Rows[0]);
}
return userInfo;
}
/// <summary>
/// 根据用户的用户名,获取用户的信息
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public UserInfo GetUserInfo(string userName)
{
string sql = "select * from UserInfo where UserName=@UserName";
SqlParameter[] pars = {
new SqlParameter("@UserName",SqlDbType.NVarChar,32)
};
pars[0].Value = userName;
DataTable da = SqlHelper.GetDataTable(sql, CommandType.Text, pars);
UserInfo userInfo = null;
if (da.Rows.Count > 0)
{
userInfo = new UserInfo();
LoadEntity(userInfo, da.Rows[0]);
}
return userInfo;
}