1. 程式人生 > >MVC + 三層 + ASP.NET 簡單登陸驗證

MVC + 三層 + ASP.NET 簡單登陸驗證

 通過製作一個登陸小案例搭建 MVC + 三層


【VIEWS】--【Shared】下建立一個母版頁: _LoginPartial.cshtml

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    <link href="~/Content/LogIn.css" rel="stylesheet" />
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }

        .nav {
            border: 2px solid border-right:none;
            overflow: hidden;
            float: center;
        }

            .nav ul li {
                float: left;
                width: 130px;
                height: 20px;
            }

                .nav ul li a {
                    width: 150px;
                    height: 30px;
                    text-align: center;
                    line-height: 28px;
                    display: block;
                    border-right: 2px solid #FFFFFF;
                    color: #FFF;
                    width: 150px;
                    font-weight: bold;
                }

                    .nav ul li a:hover {
                        font-weight: bold;
                        color: #FFFFFF;
                    }

                .nav ul li ul {
                    position: absolute;
                    display: none;
                }

                    .nav ul li ul li {
                        float: none;
                    }

                        .nav ul li ul li a {
                            width: 150px;
                            height: 40px;
                            border-right: none;
                            border-top: 1px dotted #FFFFFF;
                            background: #cc6698;
                        }

                .nav ul li:hover ul {
                    display: block;
                }

        .barStyle {
            color: #FFFFFF;
            font-weight: bold;
        }

        .style1 {
            text-align: center;
            font-family: "Meiryo UI";
            font-size: x-large;
        }
    </style>
    <title>@ViewBag.Title</title>
</head>
<body>
    <div id="header" style="background: #a6154c; width: 100%; height: 80px">
        <p style="color: #ffffff; padding: 23px" class="style1">
            <strong>User Management System</strong>
        </p>
    </div>


    @if (Request.IsAuthenticated) <span style="color:#ff6600;"> //如果登陸成功</span>
    {
        <center>
            <div class="nav" style="background: #a6154c; width: 100%; height: 30px">
                <ul>
                    <li>@Html.ActionLink("Home", "Index", "Home")</li> //主頁
                    <li>@Html.ActionLink("Log Out", "LogOut", "Account")</li>    //導航欄新增一個  log Out  選項                
                </ul>
            </div>
            <div><span>Current ID: @Context.User.Identity.Name</span> </div>  <span style="color:#ff6600;">//獲取當前登入使用者</span>
        </center>
    }
    else  <span style="color:#ff6600;">// 未登入狀態</span>
    {
        <center>
            <div class="nav" style="background: #a6154c; width: 100%; height: 30px">
                <ul>
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>  //主頁
                    <li>@Html.ActionLink("Log In", "login", "Account")</li>   //登陸選項                
                </ul>
            </div>
            <b>Pls login first!</b>  //提示需要先登入
        </center>
    }

   
    <div>
        @RenderBody()
    </div>
</body>
</html>

  注意:需要使用Request.IsAuthenticated 身份驗證,需要在Web.Config 下新增如下程式碼

<authentication mode="Forms">
      <forms loginUrl="~/Account/Login" protection="All" timeout="60" path="/" />
</authentication>


控制器:  AccountController.cs

public class AccountController : Controller
    {
        // GET: Account
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(AccountEntity account)
        {
            if (new Bll.AccountManageBll().LoginCheck(account))
            {
                FormsAuthentication.SetAuthCookie(account.LogID, true);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                ViewBag.msg = "LogID or Password error.";
                return View();
            }
        }

        public ActionResult LogOut()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index","Home");
        }
    }

檢視:【Views】--【Account】 Login.cshtml

@using Model
@model AccountEntity
@{
    ViewBag.Title = "Login";
    Layout = "~/Views/Shared/_LoginPartial.cshtml";
}

<br />
<br />
<br />
@using (Html.BeginForm("Login", "Account", FormMethod.Post))
{
    <div class="full">
        <div class="box">
            <div class="title">
                <span class="titlespan"><b>Log In</b></span>
            </div>
            <br />
            <div class="ID">
                <div><span>Login ID  </span> @Html.TextBoxFor(u => u.LogID)</div>
                <div>@Html.ValidationMessageFor(u => u.LogID, "", new { style = "color:#F00;font-size:10px" })</div>
            </div>
            <div class="password">
                <div><span>Password  </span>@Html.PasswordFor(u => u.Password)</div>
                <div>@Html.ValidationMessageFor(u => u.Password, "", new { style = "color:#F00;font-size:10px" })</div> <span style="color:#ff6600;"> //校驗不能為空</span>
            </div>
            <div class="btnLogin">
                <input type="Submit" name="Submit" value="Log In">
            </div>
        </div>
    </div>
        <div class="full">
            <br />
            <span style="color:#F00;font-size:12px;font-weight:bold">@ViewBag.msg</span><br />
        </div>
}

實體:【Model】層新建一個 AccountEntity  實體模型

    public class AccountEntity
    {
        [Required(ErrorMessage ="LogID cann't be empty!")] //Required 驗證
        public string LogID { get; set; }

        [Required(ErrorMessage = "Password cann't be empty!")]   //Required 驗證
        public string Password { get; set; }

        public AccountEntity() { } //無參建構函式
        public AccountEntity(string ID,string Pwd)  //有參建構函式 為了測試資料
        {
            LogID = ID;
            Password = Pwd;
        }
    }

【DAL】資料訪問層  AccountServiceDal.cs   

【使用資料庫才需要使用  本例項測試資料在BLL層】

        /// <summary>
        /// 獲取使用者資訊
        /// </summary>
        /// <returns></returns>
        public List<AccountEntity> GetAccountInfo()
        {
            string sqlStr = @"ProcSelAccount";  //儲存過程名
            List<AccountEntity> accountList = new List<AccountEntity>();

            using (SqlDataReader reader = SqlHelper.ExecReader(sqlStr))   //SqlHelper: SQL幫助類
            {
                while (reader.Read())
                {
                    AccountEntity account = BuildSubject(reader);
                    accountList.Add(account);
                }
            }
            return accountList;
        }

        public AccountEntity BuildSubject(SqlDataReader reader)
        {
            AccountEntity account = new AccountEntity();
            account.LogID = reader.GetString(0);
            account.Password = reader.GetString(1);
           

【BLL】業務邏輯層 AccountManageBll.cs

        public bool LoginCheck(AccountEntity account)
        {
            bool flag = false;
            // List<AccountEntity> accountList = new AccountServiceDal().GetAccountInfo();   //校驗資料庫中使用者資料,需使用此程式碼

            <span style="color:#ff0000;">//Test Account Data</span>
            List<AccountEntity> accountList = new List<AccountEntity>()  //增加兩條使用者資料
            {
                new AccountEntity("Jarvis","ABC123"),   
                new AccountEntity("Admin","admin123")
            };

            foreach (AccountEntity accountInfo in accountList)
            {
                if(accountInfo.LogID == account.LogID && accountInfo.Password == account.Password)
                {
                    flag = true;
                }
            }
            return flag;
        }


最終測試實現:

1.未登入狀態


2. 驗證


3.正確登陸


4.登陸成功


作為初學者,純分享一些小案例,有不足之處還望高人指點迷津。