.net MVC 實現基本的登陸

1,新建Login.cshtml並建立form表單:其中包括用戶名和密碼,提交圖片以及錯誤信息提示

 

<form action="Login" method="post"> 
<input type="text" name="userName">
<input type="password" name="password">
<input type="image" src="~/Content/Images/dl.gif" />
<div style="color:#db0909">@ViewBag.ErrorMessage</div>
</form>


2,Web.config中加入權限代碼(除了Login外不能訪問任何頁面):

<authentication mode="Forms">
      <forms loginUrl="~/Home/Login"  timeout="2880" />
    </authentication>
    <authorization>      
      <deny users="?" />
    </authorization>

3,寫在控制器中寫入Login:

[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Login(string userName, string password)
        {
            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
            {
                ViewBag.ErrorMessage = "資料填寫不完整";
            }
            else if (userName == "admin" && password == "admin")
            {// 這裏只有admin能夠登陸
                System.Web.Security.FormsAuthentication.RedirectFromLoginPage(userName, true);
 
               return RedirectToAction("Index", "Home");//登陸成功後的地址
            }
            else
            {
                ViewBag.ErrorMessage = "用戶或密碼錯誤";
            }
            return View();
        }

然後就完成了,很簡單吧~
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章