How to set cookie value on one page and read it from another page on asp.net website

This is my code in Login.aspx

protected void LoginButton_Click(object sender, EventArgs e) { HttpCookie loginCookie1 = new HttpCookie("loginCookie"); Response.Cookies["loginCookie1"].Value = LoginUser.UserName; Response.Cookies.Add(loginCookie1); } 

And this is at shop.aspx

 protected void btnAddCart_Click(object sender, EventArgs e) { HttpCookie myCookie = new HttpCookie(dvProduct.DataKey.Value.ToString()); myCookie["Category"] = dvProduct.DataKey["Category"].ToString(); myCookie["Product"] = dvProduct.DataKey["Product"].ToString(); myCookie["Quantity"] = txtQuantity.Text; myCookie["Price"] = dvProduct.DataKey["Price"].ToString(); myCookie.Expires = DateTime.Now.AddDays(1d); Response.Cookies.Add(myCookie); Response.Redirect("ViewCart.aspx", true); } 

I want to read the username value from a cookie (the value is set in login.aspx

+6
source share
3 answers

you basically need to request a cookie, in fact it doesn’t matter which page you are on here is the explanation for cookies

http://msdn.microsoft.com/en-us/library/ms178194.aspx

 HttpCookie aCookie = Request.Cookies["loginCookie"]; string username = Server.HtmlEncode(aCookie.Value); 
+14
source

Your code that sets loginCookie looks weird:

 HttpCookie loginCookie1 = new HttpCookie("loginCookie"); Response.Cookies["loginCookie1"].Value = LoginUser.UserName; // <--- strange!!!! Response.Cookies.Add(loginCookie1); 

Most likely, your cookie is not sent to the browser - check using an HTTP debugger such as Fiddler .

+4
source

This should do it:

 var userName = Request.Cookies["loginCookie"].Value; 
+1
source

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


All Articles