Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the cookie value in asp.net website

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"/> 
like image 607
Mark Avatar asked Dec 13 '11 13:12

Mark


People also ask

How do I view cookies in Web API?

You can retrieve cookies using something like: var userName = Request. Headers. GetCookies("userName").

What are cookie values?

Name=Value: Cookies are stored in the form of name-value pairs. Path: Specifies the webpage or directory that sets the cookie. Secure: Specifies whether the cookie can be retrieved by any server (secure or non-secure).


2 Answers

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

if(Request.Cookies["key"]!=null) {    var value=Request.Cookies["key"].Value; } 
like image 96
KV Prajapati Avatar answered Sep 24 '22 06:09

KV Prajapati


FormsAuthentication.Decrypt takes the actual value of the cookie, not the name of it. You can get the cookie value like

HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value; 

and decrypt that.

like image 41
kvc Avatar answered Sep 20 '22 06:09

kvc