1. 程式人生 > >ASP.Net之使用Cookie和Session實現自動登入

ASP.Net之使用Cookie和Session實現自動登入

一、UserLogin.aspx程式碼

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UserLogin.aspx.cs" Inherits="UserLoginNameSpace" %>

<!DOCTYPE html>

<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="登入" />
        <input type="checkbox" name="autoLogin" value="auto" />自動登入
        <span style="font-size:14px;color:red"><%=Msg %></span>
    </div>
    </form>
</body>
</html>
二、UserLogin.aspx.cs程式碼
using CZBK.ItcastProject.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UserLoginNameSpace
{
    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 = "驗證碼錯誤!!";
                }
            }
            else
            {
                //判斷Cookie中的值。
                CheckCookieInfo();
            }
           
        }
        #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))
            {
                //判斷使用者是否選擇了“自動登入”
                if (!string.IsNullOrEmpty(Request.Form["autoLogin"]))//頁面上如果有多個複選框時,只能將選中複選框的的值提交到服務端。
                {
                    HttpCookie cookie1 = new HttpCookie("cp1",userName);
                    HttpCookie cookie2 = new HttpCookie("cp2", Common.WebCommon.GetMd5String(Common.WebCommon.GetMd5String(userPwd)));
                    cookie1.Expires = DateTime.Now.AddDays(7);
                    cookie2.Expires = DateTime.Now.AddDays(7);
                    Response.Cookies.Add(cookie1);
                    Response.Cookies.Add(cookie2);
                }

                Session["userInfo"] = userInfo;
                Response.Redirect("UserInfoList.aspx");
            }
            else
            {
                Msg = msg;
            }
        }

        #endregion

        #region 校驗Cookie資訊.
        protected void CheckCookieInfo()
        {
            if (Request.Cookies["cp1"] != null && Request.Cookies["cp2"] != null)
            {
                string userName = Request.Cookies["cp1"].Value;
                string userPwd = Request.Cookies["cp2"].Value;
                //校驗
                BLL.UserInfoService UserInfoService = new BLL.UserInfoService();
                UserInfo userInfo=UserInfoService.GetUserInfo(userName);
                if (userInfo != null)
                {
                    //注意:在新增使用者或註冊使用者時一定要將使用者輸入的密碼加密以後在儲存到資料庫中。
                    if (userPwd == Common.WebCommon.GetMd5String(Common.WebCommon.GetMd5String(userInfo.UserPass)))
                    {
                        Session["userInfo"] = userInfo;
                        Response.Redirect("UserInfoList.aspx");
                    }
                }
                Response.Cookies["cp1"].Expires = DateTime.Now.AddDays(-1);
                Response.Cookies["cp2"].Expires = DateTime.Now.AddDays(-1);
            }
          

        }
        #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
    }
}
三、UserInfoList.aspx程式碼
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UserInfoList.aspx.cs" Inherits="UserInfoListNameSpace" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <a href="LogOut.ashx">退出</a> 
    </div>
    </form>
</body>
</html>
四、UserInfoList.aspx.cs程式碼

注意UserInfoList 繼承至Common.CheckSession,而CheckSession會判斷session裡面的值,以此可以判斷有session後才可以開啟對應的網頁

using CZBK.ItcastProject.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UserInfoListNameSpace
{
    public partial class UserInfoList :Common.CheckSession
    {
      
        protected void Page_Load(object sender, EventArgs e)
        {
            //if (Session["userInfo"] == null)
            //{
            //    Response.Redirect("UserLogin.aspx");
            //}
            //else
            //{
            //    Response.Write("歡迎"+((UserInfo)Session["userInfo"]).UserName+"登入本系統");
            //}
        }
    }
}
五、CheckSession.cs程式碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 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");
           }
       }
    }
}
六、ValidateImageCode.ashx.cs程式碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApp
{
    /// <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);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}