標籤:style blog http color io os ar strong for
控制器:
HomeController 這是首頁的控制器
LoginController 這是登陸的控制器
類:
CDBTemplate.cs 這是資料庫資料對應的類,裡邊描述的是資料庫的結構
首先在HomeController 控制器的返回函數
[csharp] view plaincopy
- public ActionResult Index(){...}
前面加上:
[csharp] view plaincopy
- [Authorize(Roles = "admins")]
就是這樣:
[csharp] view plaincopy
- [Authorize(Roles = "admins")]
- public ActionResult Index()
- {
- ...
- }
這條語句的意思是在這加上一個許可權驗證,只允許使用者角色是admins的使用者訪問
然後再web.config檔案裡添加:
[csharp] view plaincopy
- <authentication mode="Forms">
- <forms loginUrl="~/Login" timeout="2880" />
- </authentication>
這些的意思是給整個網站增加使用者驗證,指向的登陸介面是login這個控制器
CDBTemplate.cs檔案裡的一個類:
[csharp] view plaincopy
- public class LogOnModel
- {
- [Required]
- [Display(Name = "使用者名稱")]
- public string UserName { get; set; }
-
-
- [Required]
- [DataType(DataType.Password)]
- [Display(Name = "密碼")]
- public string Password { get; set; }
-
-
- [Display(Name = "下次自動登陸")]
- public bool RememberMe { get; set; }
- }
然後為LoginController 控制器的預設返回函數增加一個視圖Index.cshtml,在頁面裡面加上下面的代碼:
[csharp] view plaincopy
- @model Weibo.Models.LogOnModel //LogOnModel 是CDBTemplate.cs檔案裡的一個類
- @using (Html.BeginForm("Login","Login",FormMethod.Post)) {
- @Html.TextBoxFor(m => m.UserName)
- @Html.ValidationMessageFor(m => m.UserName, "請輸入使用者名稱!", new {style="color: #f00" })
- @Html.PasswordFor(m => m.Password)
- @Html.ValidationMessageFor(m => m.Password,"請輸入密碼!",new {style="color: #f00" })
- @Html.CheckBoxFor(m => m.RememberMe)
- @Html.LabelFor(m => m.RememberMe)
- @Html.ActionLink("忘記密碼", "forgotpwd", null, new {@class="rt",target="_blank" })
- <input type="submit" value="登陸微博" />
- }
在上面的代碼裡Html.BeginForm("Login","Login",FormMethod.Post)方法的第一個參數的意思是指定要調用的 控制器的方法的名字,第二個參數的意思是控制器的名字,第三個參數的意思是用什麼方法把表單提交給伺服器,這裡我們為了安全,選擇用post方式提交。
然後在LoginController 控制器中增加這麼一個方法:
[csharp] view plaincopy
- [HttpPost, ActionName("Login")]
- public void Login(FormCollection collection)
- {
- object obj = SqlHelper.ExecuteScalar("select UserId from CDBUsers where [email protected] and [email protected]",
- new SqlParameter("@uname", collection[0]),
- new SqlParameter("@pwd", Weibo.Models.Myencrypt.myencrypt(collection[1])));
-
-
- if (obj != null)
- {
- FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
- 1,
- collection[0],
- DateTime.Now,
- DateTime.Now.AddMinutes(30),
- false,
- "admins"
- );
- string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
- System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
- System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
- }
-
-
- Response.Redirect("~/");
- }
[Asp.Net MVC4]驗證使用者登入實現