国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

Asp.net mvc驗證用戶登錄之Forms實現(xiàn)詳解

2024-07-10 12:54:39
字體:
供稿:網(wǎng)友

MVC開發(fā)的時候,我們都會遇到用戶登錄Forms,而訪問的時候也能直接轉(zhuǎn)到視圖,下面錯新技術(shù)頻道小編為大家介紹Asp.net mvc驗證用戶登錄之Forms實現(xiàn)詳解。

這里我們采用asp.net mvc 自帶的AuthorizeAttribute過濾器驗證用戶的身份,也可以使用自定義過濾器,步驟都是一樣。

第一步:創(chuàng)建asp.net mvc項目, 在項目的App_Start文件夾下面有一個FilterConfig.cs,在這個文件中可以注冊全局的過濾器。我們在文件中添加AuthorizeAttribute過濾器如下:

public class FilterConfig {  public static void RegisterGlobalFilters(GlobalFilterCollection filters)  {   filters.Add(new HandleErrorAttribute());   //將內(nèi)置的權(quán)限過濾器添加到全局過濾中   filters.Add(new System.Web.Mvc.AuthorizeAttribute());  } }

第二步:在web.config配置文件中修改網(wǎng)站的身份認證為mode="Forms"

<system.web> <!--Cockie名稱,當用未登入時跳轉(zhuǎn)的url--> <authentication mode="Forms">  <forms name="xCookie" loginUrl="~/Login/Index" protection="All" timeout="60" cookieless="UseCookies"></forms> </authentication> <compilation debug="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5" /> </system.web>

提示:配置name值作為最終生成的cookie的名稱,loginUrl指定當用戶未登入是跳轉(zhuǎn)的頁面,這里挑戰(zhàn)到登入頁面

第三步:添加用戶登入相關(guān)的控制器和視圖

創(chuàng)建LoginController控制器:

?

public class LoginController : Controller {  [HttpGet]  [AllowAnonymous]  public ActionResult Index()  {   return View();  }  [HttpPost]  [AllowAnonymous]  public ActionResult Login(User user)   {   if (!user.Username.Trim().Equals("liuxin") || !user.Password.Trim().Equals("abc"))   {    ModelState.AddModelError("", "用戶名或密碼錯誤");    return View("index", user);   }   //if (!user.Username.Trim().Equals("liuxin")) {   // ModelState.AddModelError("Username", "用戶名錯誤");   // return View("index", user);   //}   //if (!user.Password.Trim().Equals("abc")) {   // ModelState.AddModelError("Password", "密碼錯誤");   // return View("index", user);   //}   user.Id = Guid.NewGuid().ToString("D");//為了測試手動設(shè)置一個用戶id   FormsAuthHelp.AddFormsAuthCookie(user.Id, user, 60);//設(shè)置ticket票據(jù)的名稱為用戶的id,設(shè)置有效時間為60分鐘   return Redirect("~");  }  [HttpGet]  public ActionResult Logout() {   FormsAuthHelp.RemoveFormsAuthCookie();   return Redirect("~/Login/Index");  } }

特別注意:Index和Login這兩個方法得使用“[AllowAnonymous]”指明這兩個方法可以匿名訪問,否則由于過濾器不允許匿名訪問,導(dǎo)致登入頁面和用戶提交都無法進行。顯然這不是我們希望看到的。

提示:為了測試方便這邊的用戶的數(shù)據(jù)是寫死的,用戶的id也是臨時生成了一個

public class User {  public string Id { get; set; }  public string Username { get; set; }  public string Password { get; set; } }

創(chuàng)建登入視圖:

@{ Layout = null; ViewBag.Title = "Index";}<h3>您尚未登入,請登入</h3>@using(Html.BeginForm("Login", "Login", FormMethod.Post)){ @Html.Label("Username", "用戶名:")@Html.TextBox("Username", null, new { id = "Username", placeholder = "請輸入用戶名" }) @Html.ValidationMessage("Username")<br/> @Html.Label("Password", "密 碼:")@Html.TextBox("Password", null, new { id = "Password", placeholder = "請輸入密碼" }) @Html.ValidationMessage("Password")<br/> <input type="submit" value="登入" /> <input type="reset" value="重置" /> @Html.ValidationSummary(true)}

提示:當檢測到用戶未登入,則跳轉(zhuǎn)到web.config中配置的url頁面,當用戶填寫密碼并提交時,用戶輸入的數(shù)據(jù)會提交到LoginController控制器下的Login方法,驗證用戶的輸入,認證失敗重新返回到登入界面,當認證成功,將會執(zhí)行

<<***FormsAuthHelp.AddFormsAuthCookie(user.Id, user, 60);//設(shè)置ticket票據(jù)的名稱為用戶的id,設(shè)置有效時間為60分鐘***>>,這條語句的作用是生成一個ticket票據(jù),并封裝到cookie中,asp.net mvc正式通過檢測這個cookie認證用戶是否登入的,具體代碼如下

第四步:將用戶信息生成ticket封裝到cookie中

?

public class FormsAuthHelp {  /// <summary>  /// 將當前登入用戶的信息生成ticket添加到到cookie中(用于登入)  /// </summary>  /// <param name="loginName">Forms身份驗證票相關(guān)聯(lián)的用戶名(一般是當前用戶的id,作為ticket的名稱使用)</param>  /// <param name="userData">用戶信息</param>  /// <param name="expireMin">有效期</param>  public static void AddFormsAuthCookie(string loginName, object userData, int expireMin)  {   //將當前登入的用戶信息序列化   var data = JsonConvert.SerializeObject(userData);   //創(chuàng)建一個FormsAuthenticationTicket,它包含登錄名以及額外的用戶數(shù)據(jù)。   var ticket = new FormsAuthenticationTicket(1,    loginName, DateTime.Now, DateTime.Now.AddDays(1), true, data);   //加密Ticket,變成一個加密的字符串。   var cookieValue = FormsAuthentication.Encrypt(ticket);   //根據(jù)加密結(jié)果創(chuàng)建登錄Cookie   //FormsAuthentication.FormsCookieName是配置文件中指定的cookie名稱,默認是".ASPXAUTH"   var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue)   {    HttpOnly = true,    Secure = FormsAuthentication.RequireSSL,    Domain = FormsAuthentication.CookieDomain,    Path = FormsAuthentication.FormsCookiePath   };   //設(shè)置有效時間   if (expireMin > 0)    cookie.Expires = DateTime.Now.AddMinutes(expireMin);   var context = HttpContext.Current;   if (context == null)    throw new InvalidOperationException();   //寫登錄Cookie   context.Response.Cookies.Remove(cookie.Name);   context.Response.Cookies.Add(cookie);  }  /// <summary>  /// 刪除用戶ticket票據(jù)  /// </summary>  public static void RemoveFormsAuthCookie() {   FormsAuthentication.SignOut();  } }

第五步:測試執(zhí)行

1. 啟動網(wǎng)站輸入相應(yīng)的網(wǎng)址:如下圖

2. 此時用戶尚未登入將會跳轉(zhuǎn)到登入界面:如下圖

3.輸入錯誤的密碼會重新跳轉(zhuǎn)到登入界面并提示出錯

4. 輸入正確的用戶名密碼

5.點擊用戶退出會刪除掉cookie所以又會跳轉(zhuǎn)到登入界面。

源碼下載地址。

通過錯新技術(shù)頻道小編介紹的Asp.net mvc驗證用戶登錄之Forms實現(xiàn)詳解,大家對這些知識有沒有了解更多呢,感興趣就收藏js.VeVb.com吧!

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 无棣县| 梅州市| 大新县| 清水河县| 辉县市| 娱乐| 股票| 巴塘县| 洛宁县| 高雄市| 高青县| 宜州市| 万宁市| 永福县| 伊春市| 邵武市| 镇原县| 万荣县| 古蔺县| 桦川县| 丁青县| 澳门| 正阳县| 唐河县| 潼南县| 泸定县| 托克托县| 华安县| 临沭县| 绥阳县| 武冈市| 丹江口市| 威信县| 沿河| 原阳县| 屯留县| 罗山县| 石嘴山市| 会宁县| 武山县| 阿荣旗|