[ACCEPTED]-How to check if cookies are empty or not-asp.net-mvc-3

Accepted answer
Score: 13

Just check if the cookie is null:

if(Request.Cookies["randomHash"] != null)
{
   //do something
}

NOTE: The 16 "Better" way of doing this is to write good 15 code that is both readable and reliable. It 14 doesn't assign empty string because this 13 is not how C# works, you are trying to call 12 the Value property on a null object (HttpCookie) - you cannot 11 use null objects because there is nothing 10 to use.

Converting to an int you still need 9 to avoid parse errors, but you can use this 8 built in method:

int.TryParse(cookieString, out userID);

which brings on another 7 point? Why are you storing the userID in 6 a cookie? this can be changed by the end 5 user - I don't know how you plan on using 4 this but would I be right to assume this 3 is a big security hole?


or with a little 2 helper function:

public string GetCookieValueOrDefault(string cookieName)
{
   HttpCookie cookie = Request.Cookies[cookieName];
   if(cookie == null)
   {
      return "";
   }  
   return cookie.Value;
}

then...

string randomHash = GetCookieValueOrDefault("randomHash");

Or with an Extension 1 method:

public static string GetValueOrDefault(this HttpCookie cookie)
{
   if(cookie == null)
   {
      return "";
   }  
   return cookie.Value;  
}

then...

string randomHash = Request.Cookies["randomHash"].GetValueOrDefault();

More Related questions