Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set cookie value in one page and read it from another page in a 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 in 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 value of username from cookie(value set in login.aspx

like image 569
techblog Avatar asked Apr 14 '12 04:04

techblog


2 Answers

you basically need to request the cookie it does not really matter on what page you are here is an explanation about cookies

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

HttpCookie aCookie = Request.Cookies["loginCookie"];
string username = Server.HtmlEncode(aCookie.Value);
like image 71
COLD TOLD Avatar answered Oct 21 '22 06:10

COLD TOLD


Your code that sets loginCookie looks strange:

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

Most likely your cookie does not get send to browser - check with HTTP debugger like Fiddler.

like image 35
Alexei Levenkov Avatar answered Oct 21 '22 08:10

Alexei Levenkov