2012-05-14 92 views
4

我怎麼能創造一步一個cookie一步,在MVC創建的Cookie 3

存儲用戶登錄ID和密碼時,他/她點擊記住?選項

和我刨一定時間後殺死這個cookie

回答

14

Cookies是創建以同樣的方式,因爲他們在普通的舊ASP.NET,你只需要訪問Response

 public ActionResult Login(string username, string password, bool rememberMe) 
     { 
      // validate username/password 

      if (rememberMe) 
      { 
       HttpCookie cookie = new HttpCookie("RememberUsername", username); 
       Response.Cookies.Add(cookie); 
      } 

      return View(); 

     } 

但是,如果您正在使用窗體身份驗證,你可以讓你的FormsAuth票的Cookie持續性:

 public ActionResult Login(string username, string password, bool rememberMe) 
     { 
      // validate username/password 

      FormsAuthentication.SetAuthCookie(username, rememberMe); 

      return View(); 

     } 

你可以這樣寫的餅乾:

public ActionResult Index() 
{ 
    var cookie = Request.Cookies["RememberUsername"]; 

    var username = cookie == null ? string.Empty : cookie.Value; // if the cookie is not present, 'cookie' will be null. I set the 'username' variable to an empty string if its missing; otherwise i use the cookie value 

    // do what you wish with the cookie value 

    return View(); 
} 

如果您使用表單認證並且用戶已登錄,您可以像這樣訪問其用戶名:

public ActionResult Index() 
{ 


    var username = User.Identity.IsAuthenticated ? User.Identity.Name : string.Empty; 

    // do what you wish with user name 

    return View(); 
} 

可以解密和讀取票證的內容。如果需要,您甚至可以在票證中存儲少量的自定義數據。 See this article for more info.

+0

嗨,我有兩件事要問.... 1。如果我們想查看視圖中存儲在cookie中的數據,那麼我們如何看待或調用它? –

+0

和2.這個cookie和FormsAuthentication票據cookie之間的主要區別是什麼?或者兩者是相同的....? –

+1

表單身份驗證是一種在ASP.NET中驗證用戶身份的方法。你不必使用它,但它被廣泛使用。 「票證」是表單驗證模塊在接收到每個請求時解密並驗證的加密cookie。如果票據cookie丟失或無效,用戶不會被視爲登錄。通常,您不關心FormsAuth Cookie的內容,只相信該模塊正在完成其工作(它很好)。我會通過如何閱讀cookies來改進我的答案。 – HackedByChinese