Create Cookie in MVC 3

How can I create a cookie step by step,

which stores the user id and password when he clicks "Remember me"? Option

and I plan to kill this cookie after a certain time

+4
source share
1 answer

Cookies are created just like in plain old ASP.NET, you just need to access 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(); } 

However, if you use Forms Auth, you can simply save the FormsAuth cookie:

  public ActionResult Login(string username, string password, bool rememberMe) { // validate username/password FormsAuthentication.SetAuthCookie(username, rememberMe); return View(); } 

You can read cookies as follows:

 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(); } 

If you use forms authentication and the user is logged in, you can access their username as follows:

 public ActionResult Index() { var username = User.Identity.IsAuthenticated ? User.Identity.Name : string.Empty; // do what you wish with user name return View(); } 

You can decrypt and read the contents of the ticket. You can even store small amounts of user data on a ticket if you need to. See this article for more information.

+14
source

Source: https://habr.com/ru/post/1412334/


All Articles