public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void OnInit(EventArgs e)
{
if (Session["uInfo"] == null)
{
//1.判断用户是否勾选记住三天免登陆
if (Request.Cookies["uid"] != null)
{
var TableAdapter = new WebApplication2.DataSet1TableAdapters.BlogUserTableAdapter();
var DataTable = TableAdapter.GetDataByUID(int.Parse(Request.Cookies["uid"].Value));
//3.将实体存入session中
Session["uInfo"] = DataTable.Rows[0];
return;
}
//4.跳转到登陆页面
Response.Redirect("/Login.aspx");
}
base.OnInit(e);
}
}
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
var TableAdapter = new WebApplication2.DataSet1TableAdapters.BlogUserTableAdapter();
var DataTable = TableAdapter.GetDataByName(txtUserName.Text);
//2.判断用户集合是否存在
if (DataTable.Rows.Count > 0)
{
//3.将用户信息保存到session中
Context.Session["uInfo"] = DataTable.Rows[0];
//4.判断用户是否选中了记住登陆
if (ckbThree.Checked)
{
//5.记住了就将用户id存入cookie中
HttpCookie cookie = new HttpCookie("uid", DataTable.Rows[0]["uid"].ToString());
cookie.Expires = DateTime.Now.AddDays(3);
Context.Response.Cookies.Add(cookie);
}
Response.Write("<script>alert('登陆成功');window.location='WebForm1.aspx'</script>");
}
else
{
Response.Write("<script>alert('登陆失败,请重新登陆');window.location='/Login.aspx'</script>");
}
Response.End();
}
}
<form id="form1" runat="server">
<div>
登录名:<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
记住三天免登录:<asp:CheckBox ID="ckbThree" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
</form>