'Cookie value is null

I'm trying to read the value of a cookie that I have set but it keeps coming back null. This is how I'm setting the cooking: -

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

And these are the ways that I've tried to read it: -

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

The above ways all return a null value. I know that the cookie is definitely there as I can see it in the developer tools console



Solution 1:[1]

Trying the same with Assigning some values to the variable, Just check this code which is working fine,

Set the Cookie

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

Get the cookie values

These three is working fine...

string username = "";

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

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

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

Solution 2:[2]

Try this

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.");

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Smit Patel
Solution 2 Soner