Asp.net-mvc – Create Cookie in MVC 3

asp.netasp.net-mvcasp.net-mvc-3

How can i create a cookie step by step,

that stores the user login id and password when he/she clicks Remember Me? option

and i am planing to kill this cookie after certain time

Best Answer

Cookies are created the same way as they are in plain old ASP.NET, you just need to access the 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're using Forms Auth, you can just make your FormsAuth ticket cookie persistent:

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

            FormsAuthentication.SetAuthCookie(username, rememberMe);

            return View();

        }

You can read cookies like this:

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 are using Forms Authentication and the user is logged in, you can access their username like this:

public ActionResult Index()
{


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

    // do what you wish with user name

    return View();
}

It is possible to decrypt and read the contents of a ticket. You can even store small amounts of custom data in the ticket, if you need to. See this article for more info.