Cookie值为null

时间:2016-03-11 10:57:29

标签: c# cookies

我试图读取我已设置的cookie的值,但它一直返回null。这就是我设置烹饪的方式: -

string username = "Shazoo";
HttpCookie ck = new HttpCookie("mycookie");
ck.Expires.AddDays(30);
ck.Values.Add("username", username);
Response.Cookies.Add(ck);

这些是我尝试阅读的方式: -

  1. username = Request.Cookies.Get("mycookie").Values.Get("username");

  2. username = Request.Cookies["mycookie"]["username"];

  3. ck = new HttpCookie("mycookie"); username = ck["username"];

  4. ck = Request.Cookies["mycookie"]; username = ck["username"];

  5. 以上方式都返回null值。我知道cookie肯定存在,因为我可以在开发人员工具控制台中看到它

2 个答案:

答案 0 :(得分:0)

尝试为变量分配一些值,只需检查一下这个正常工作的代码,

设置Cookie

var username = "abcd0";
HttpCookie ck = new HttpCookie("mycookie");
ck.Expires.AddDays(30);
ck.Values.Add("username", username);
Response.Cookies.Add(ck);

获取Cookie值

这三个工作正常......

string username = "";

username = Request.Cookies.Get("mycookie").Values.Get("username");

username = Request.Cookies["mycookie"]["username"];

ck = Request.Cookies["mycookie"];
username = ck["username"]; 

答案 1 :(得分:0)

试试这个

HttpCookie myCookie = new HttpCookie("MyTestCookie");
DateTime now = DateTime.Now;

// Set the cookie value.
myCookie.Value = now.ToString();
// Set the cookie expiration date.
myCookie.Expires = now.AddYears(50); // For a cookie to effectively never expire

// Add the cookie.
Response.Cookies.Add(myCookie);

Response.Write("<p> The cookie has been written.");