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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10151045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 12:39:52  来源:igfitidea点击:

How can I set cookie value in one page and read it from another page in a asp.net website

c#asp.netcookies

提问by techblog

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 中设置的值

采纳答案by COLD TOLD

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

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

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

回答by Rick Strahl

This should do it:

这应该这样做:

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

回答by Alexei Levenkov

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 调试器进行检查。