如何在cookie中保存字符串?

时间:2014-01-17 11:33:20

标签: c# asp.net

我使用以下代码将我的文本存储在cookie中。

 HttpCookie Location = new HttpCookie("Location");
            Response.Cookies.Remove("Location");
            Response.Cookies.Add(Location);
               Location.Value = "Sample Text";
 DateTime deathDate = DateTime.Now.AddYears(1);
            Location.Expires = deathDate;
 Response.Cookies.Add(Location);

在以下代码中使用Ant来检索Page_Load中的cookie:

 HttpCookie Location = new HttpCookie("Location");
            Location = Request.Cookies["Location"];
            if (Location != null)
            {
                ltlLocation.Text = Location.ToString();                            
            }

现在问题是:一旦我重定向到其他页面并返回到此页面: 我的文字工具(ltlLocation.Text)将显示“System.Web.HttpCookie”,而不是显示字符串值“Sample Text”。 那我的代码有什么问题呢?

2 个答案:

答案 0 :(得分:1)

您错过了Value媒体资源:

ltlLocation.Text = Request.Cookies["Location"].Value;

或者从你的例子:

ltlLocation.Text = Location.Value;

答案 1 :(得分:1)

 if(Request.Cookies["Location"] != null)
      {
           ltlLocation.Text = Request.Cookies["Location"].Value;
      }