Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Cookie in 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

like image 442
P_A_1 Avatar asked Dec 10 '22 00:12

P_A_1


1 Answers

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.

like image 118
moribvndvs Avatar answered Dec 28 '22 02:12

moribvndvs