2013-04-24 2 views
0

SimpleMemberShip과 함께 ASP.net MVC4를 사용하고 있습니다.Simplemembership Login and RemeberMe ASP.Net MVC4

나 기억하기 확인란을 선택하고 쿠키에서 다시로드하면 사용자 이름을 저장하기 만하면됩니다.

로그인이 정상적으로 작동하며 RememberMe가 true로 설정됩니다. 하지만 Request.Cookies [FormsAuthentication.FormsCookieName]은 항상 null입니다. 이것이 어떻게 작동해야하는지 혼란 스럽다.

로그인 컨트롤러 :

[HttpPost] 
    [AllowAnonymous] 
    [ValidateAntiForgeryToken] 
    public ActionResult Index(LoginModel model, string returnUrl) 
    { 
     bool RememberMe = model.RememberMe == "on" ? true : false; 
     if (WebSecurity.Login(model.UserName, model.Password, persistCookie: RememberMe)) 
     { 
      return RedirectToLocal(returnUrl); 
     } 

     // If we got this far, something failed, redisplay form 
     ModelState.AddModelError("", "The user name or password provided is incorrect."); 
     return View(model); 
    } 

로그인 페이지 컨트롤러 :

[AllowAnonymous] 
    public ActionResult Index(string returnUrl) 
    { 
     // load user name 
     HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; 


     if (authCookie != null) 
     { 
      FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value); 
      ViewBag.Username = Server.HtmlEncode(ticket.Name); 
      ViewBag.RememberMeSet = true; 
     } 
     else 
     { 
      ViewBag.RememberMeSet = false; 
     } 
     ViewBag.ReturnUrl = returnUrl; 
     return View(); 
    } 
+0

왜 그냥 WebSecurity.CurrentUserName를 사용하지 않는 재산. http://msdn.microsoft.com/en-us/library/webmatrix.webdata.websecurity.currentusername(v=vs.111).aspx –

+0

폼 인증으로 사용자 이름 텍스트 상자에 쿠키에 저장된 사용자 이름을로드하기 만하면됩니다. 로그인 페이지에서 – Simon

+0

로그인 페이지에서 사용하려는 경우 사용자가 로그인하지 않은 것으로 가정합니다. 로그인하지 않으면 쿠키가 null이됩니다. 그들이 로그인되어 있다면 당신이하려는 것은 잘될 것입니다. 그러나 이전에 언급했듯이, WebSecurity.CurrentUserName을 호출하여 쿠키에서 가져 오기보다는 사용자 이름을 얻는 것이 더 쉽습니다. –

답변

1

내가 원한은 사용자 이름은 "나를 기억 '체크 박스를 클릭하여 저장하세요. 로그인 페이지에 아무 쓸모가 없도록 로그인하지 않으면 쿠키가 null임을 이해합니다. 참고로 아래에 내 솔루션을 추가했습니다.

핸들 로그인 요청 컨트롤러 :

 [HttpPost] 
     [AllowAnonymous] 
     [ValidateAntiForgeryToken] 
     public ActionResult Index(LoginModel model, string returnUrl) 
     { 
      // handle remembering username on login page 
      bool RememberMe = model.RememberMe == "on" ? true : false; 
      HttpCookie existingCookie = Request.Cookies["xxx_username"]; 

      if (RememberMe) 
      { 
       // check if cookie exists and if yes update 
       if (existingCookie != null) 
       { 
        // force to expire it 
        existingCookie.Expires = DateTime.Today.AddMonths(12); 
       } 
       else 
       { 
        // create a cookie 
        HttpCookie newCookie = new HttpCookie("xxx_username", model.UserName); 
        newCookie.Expires = DateTime.Today.AddMonths(12); 
        Response.Cookies.Add(newCookie); 
       } 
      } 
      else 
      { 
       // remove cookie 
       if (existingCookie != null) 
       { 
        Response.Cookies["xxx_username"].Expires = DateTime.Now.AddDays(-1); 
       } 
      } 

      if ((!string.IsNullOrEmpty(model.UserName)) && (!string.IsNullOrEmpty(model.Password))) 
      { 
       if (WebSecurity.Login(model.UserName, model.Password, RememberMe)) 
       { 
        return RedirectToLocal(returnUrl); 
       } 
      } 

      // If we got this far, something failed, redisplay form 
      TempData["ErrorMsg"] = "Login failed"; 
      return View(model); 
     } 

디스플레이 로그인 페이지 컨트롤러 : 당신은 단지 현재 로그인 한 사용자의 사용자 이름을 원하는 경우

[AllowAnonymous] 
    public ActionResult Index(string returnUrl) 
    { 
     // load user name 
     HttpCookie existingCookie = Request.Cookies["xxx_username"]; 
     if (existingCookie != null) 
     { 
      ViewBag.Username = existingCookie.Value; 
      ViewBag.RememberMeSet = true; 
     } 
     else 
     { 
      ViewBag.RememberMeSet = false; 
     } 
     ViewBag.ReturnUrl = returnUrl; 
     return View(); 
    }