Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.NET cookies returning null

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

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.

like image 535
Rickyman35 Avatar asked Dec 10 '22 07:12

Rickyman35


2 Answers

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"];
  }

}
like image 107
NotMe Avatar answered Dec 24 '22 01:12

NotMe


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
like image 20
Praneeth Avatar answered Dec 24 '22 01:12

Praneeth