如何在一个页面中设置cookie值并从asp.net网站的另一个页面中读取它

时间:2021-12-29 06:00:49

This is my code in Login.aspx

这是我在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

这是在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

我想从cookie中读取用户名的值(在login.aspx中设置的值

3 个解决方案

#1


14  

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

你基本上需要请求cookie,你在这里的页面上关于cookie的解释并不重要

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

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

#2


5  

Your code that sets loginCookie looks strange:

你设置loginCookie的代码看起来很奇怪:

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.

很可能你的cookie没有被发送到浏览器 - 请查看像Fiddler这样的HTTP调试器。

#3


1  

This should do it:

这应该这样做:

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

#1


14  

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

你基本上需要请求cookie,你在这里的页面上关于cookie的解释并不重要

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

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

#2


5  

Your code that sets loginCookie looks strange:

你设置loginCookie的代码看起来很奇怪:

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.

很可能你的cookie没有被发送到浏览器 - 请查看像Fiddler这样的HTTP调试器。

#3


1  

This should do it:

这应该这样做:

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