开发者

Asp.NET cookies returning null

开发者 https://www.devze.com 2023-03-25 21:05 出处:网络
I\'m trying to save a cookie when a button is clicked like so... 开发者_JAVA百科protected void btn_login_Click(object sender, EventArgs e)

I'm trying to save a cookie when a button is clicked like so...

开发者_JAVA百科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);
}

Then on the page_load I am reading the cookie...

protected void Page_Load(object sender, EventArgs e)
{
    string a = Response.Cookies["test"]["work"];
}

But it keeps coming back null. I am running this under localhost and I read that cookies won't save under localhost so I edited my host file to say 127.0.0.1 test.cookie.com When I used Fiddler to see what was getting posted to the header of the page. It looks like this...

test/work = now test =

So I can see that it is getting set but for some reason when I read it in it returns null.


On the page_load change it from Response.Cookies to Request.Cookies.

The Response object is for sending data back. The Request object has data that is passed to you.

example:

String a = Request.Cookies["test"]["work"];

Note that if the cookie doesn't exist, then this will cause a null reference exception.

Usually you should do something like:

protected void Page_Load(object sender, EventArgs e) {
  HttpCookie cookie = Request.Cookies["test"];
  String a = String.Empty;

  if (cookie != null) {
    a = cookie["work"];
  }

}


Try this

Response.Cookies["work"].Value = "Value1"

Refer this for more information.

On pageload for reading the cookie try

string value = Request.Cookies["work"].Value
0

精彩评论

暂无评论...
验证码 换一张
取 消