当点击一个按钮时,我正试图保存一个cookie … protected void btn_login_Click(object sender, EventArgs e){ HttpCookie cookie = new HttpCookie("test"); cookie["work"] = "now"; cookie.Expires = DateTime.Now + new TimeSpan(1, 0, 0
protected void btn_login_Click(object sender, EventArgs e) { HttpCookie cookie = new HttpCookie("test"); cookie["work"] = "now"; cookie.Expires = DateTime.Now + new TimeSpan(1, 0, 0, 0); cookie.Domain = ".cookie.com"; Response.Cookies.Add(cookie); }
然后在page_load上我正在阅读cookie …
protected void Page_Load(object sender, EventArgs e) { string a = Response.Cookies["test"]["work"]; }
但它不断回归无效.我在localhost下运行它,我读到cookie不会保存在localhost下,所以我编辑了我的主机文件
127.0.0.1 test.cookie.com
当我使用Fiddler查看发布到页面标题的内容时.看起来像这样……
test / work = now
test =
所以我可以看到它已经设置但是由于某种原因,当我在其中读取它时返回null.
在page_load上将它从Response.Cookies更改为Request.Cookies.Response对象用于发回数据. Request对象包含传递给您的数据.
例:
String a = Request.Cookies["test"]["work"];
请注意,如果cookie不存在,那么这将导致空引用异常.
通常你应该这样做:
protected void Page_Load(object sender, EventArgs e) { HttpCookie cookie = Request.Cookies["test"]; String a = String.Empty; if (cookie != null) { a = cookie["work"]; } }