在ASP.NET MVC中使用FormsAuthenticationu驗證一直卡在登入畫面的原因解法
ASP.NET MVC 5在登入與權限控管中,微軟似乎是推薦使用ASP.NET Identity,最簡單的使用方式就是在新建專案時就將預設的無驗證改成第二項的個別使用者帳戶功能。 不過我在做小專案時,選的是無驗證,想體驗[AuthorizeAttribute]的權限驗證功能,似乎最簡單的方式是使用.net早期的FormsAuthenticationu驗證,看別人的文章也講的很簡單,複製三段code,登入登出的功能就完成了。 小弟不幸的一用之下,我的登入功能在登入成功後又重新導回登入畫面,形成無窮迴圈卡了一個小時。 [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public ActionResult Login(LoginViewModel user) { if (ModelState.IsValid) { User u = _userService.Find(user.ID , user.Password); if(u != null) { FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, u.ID, DateTime.UtcNow, DateTime.UtcNow.AddMinutes(90), isPersistent: true, userData: u.Name, cookiePath: FormsAuthentication.FormsCookiePath ); string encTicket = FormsAuthentication.Encrypt(ticket); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket) { Secure = true, HttpOnly = true }; Response.Cookies.Add(cookie); return RedirectToAction("Index", "Lectures"); } } ModelState.AddModelError("", "無效的帳號或密碼。"); return View(user); } 這個問題關鍵字很難下,一眼看過去會覺得大家的程式碼差不多,但問題發生的原因是在於我的程式碼比別人的Cookies有多了一個Secure = true的設定,當下還真的覺得沒什麼,安全很重要,認為這是一個正常的設定,結果眉角在這裡。 ...