I need to check if cookie is present with value or not. But I wonder if there is some quick and good way of doing so since if I need to check 3 cookies it seems bad to check with if or try.
Why it does not assign empty string to my variable if cookie is not present? Instead it shows Object reference not set to an instance of an object.
My code (it works, but it seems too big for this task, I think there should be a better way of doing this)
// First I need to asign empty variables and I don't like this
string randomHash = string.Empty;
string browserHash = string.Empty;
int userID = 0;
// Second I need to add this huge block of try/catch just to get cookies
// It's fine since I need all three values in this example so if one fails all fails
try
{
randomHash = Convert.ToString(Request.Cookies["randomHash"].Value);
browserHash = Convert.ToString(Request.Cookies["browserHash"].Value);
userID = Convert.ToInt32(Request.Cookies["userID"].Value);
}
catch
{
// And of course there is nothing to catch here
}
As you can see I have this huge block just to get cookies. What I would like is something like this:
// Gives value on success, null on cookie that is not found
string randomHash = Convert.ToString(Request.Cookies["randomHash"].Value);
string browserHash = Convert.ToString(Request.Cookies["browserHash"].Value);
int userID = Convert.ToInt32(Request.Cookies["userID"].Value);
Edit
Maybe I can somehow override the .Value method to my liking?
Just check if the cookie is null:
NOTE: The “Better” way of doing this is to write good code that is both readable and reliable. It doesn’t assign empty string because this is not how C# works, you are trying to call the
Valueproperty on anullobject (HttpCookie) – you cannot use null objects because there is nothing to use.Converting to an
intyou still need to avoid parse errors, but you can use this built in method:which brings on another point? Why are you storing the userID in a cookie? this can be changed by the end user – I don’t know how you plan on using this but would I be right to assume this is a big security hole?
or with a little helper function:
then…
Or with an Extension method:
then…