How to get the cookie value in asp.net website

Mark picture Mark · Dec 13, 2011 · Viewed 162.8k times · Source

I am creating a cookie and storing the value of username after succesfull login. How can I access the cookie when the website is opened. If the cookie exist I want to fill the username text box from the cookie value. And how to decrypt the value to get the username. I am doing server side validation by getting the userdetails from the database. I am using vs 2010 with c#

FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
    DateTime.Now.AddYears(1), chk_Rememberme.Checked, "User Email");
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);

if (chk_Rememberme.Checked)
{
    ck.Expires = tkt.Expiration;
    ck.Path = FormsAuthentication.FormsCookiePath;
    Response.Cookies.Add(ck);
}

cookie is created with name as .YAFNET_Authentication and content is encrypted

Webconfig:

  <forms name=".YAFNET_Authentication" loginUrl="Home.aspx"
  protection="All" timeout="15000" cookieless="UseCookies"/>

Answer

adatapost picture adatapost · Dec 13, 2011

You may use Request.Cookies collection to read the cookies.

if(Request.Cookies["key"]!=null)
{
   var value=Request.Cookies["key"].Value;
}