标签:
SetCookie
protected void Page_Load(object sender, EventArgs e)
{
Response.Cookies["cp1"].Value = "tom";
Response.Cookies["cp1"].Expires = DateTime.Now.AddDays(3);
//删除cookie
//Response.Cookies["cp1"].Expires = DateTime.Now.AddDays(-1);
//当用户再次访问我们网站的时候浏览器一看是过期的cookie,就不会带着它了
}
GetCookie
protected void Page_Load(object sender, EventArgs e)
{
if(Request.Cookies["cp1"]!=null)
{
string value = Request.Cookies["cp1"].Value;
Response.Write(value);
}
}
RememberUserName
public string UserName { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Cookies["userName"] != null)//cookie有值
{
string name = Request.Cookies["userName"].Value;
UserName = name;
//重新写一遍
Response.Cookies["userName"].Value = name;
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(3);
}
else//cookie没有值
{
if (IsPostBack)
{
string name = Request["txtName"];
Response.Cookies["userName"].Value = name;
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(3);
}
}
}
RememberLoginState
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
IsLoginOk();
}
else
{
//如果是Get请求会把cookie里面的值发过来,这个时候进行校验
IsCheckCookieLoginOk();
}
}
/// <summary>
/// 校验Cookie值
/// </summary>
private void IsCheckCookieLoginOk()
{
if(Request["cookie1"]!=null && Request["cookie2"]!=null)
{
//拿到cookie里面存的用户名密码
string userName = Request.Cookies["cookie1"].Value;
string userPwd = Request.Cookies["cookie2"].Value;
if(userName=="admin")
{
if(userPwd==Common.StringToMD5.GetMD5Value("123"))
{
//给Session复制
Response.Redirect("/Test.aspx");
}
}
Response.Cookies["cookie1"].Expires = DateTime.Now.AddDays(-1);
Response.Cookies["cookie2"].Expires = DateTime.Now.AddDays(-1);
}
}
/// <summary>
/// 判断用户名密码是否正确
/// </summary>
private void IsLoginOk()
{
//拿到用户名密码
string userName = Request["txtName"];
string userPwd = Request["txtPwd"];
if (userName == "admin" && userPwd == "123")
{
//用户选择了记住我
if (!string.IsNullOrEmpty(Request["checkMe"]))
{
Response.Cookies["cookie1"].Value = userName;
Response.Cookies["cookie2"].Value = Common.StringToMD5.GetMD5Value(userPwd);
Response.Cookies["cookie1"].Expires = DateTime.Now.AddDays(3);
Response.Cookies["cookie2"].Expires = DateTime.Now.AddDays(3);
}
Response.Redirect("/Test.aspx");
}
}
}
标签:
原文地址:http://www.cnblogs.com/bidianqing/p/4217057.html