• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 228
  • Last Modified:

How can I check if a cookie value has been set in C#?

I have a situation where I won't know whether or not a cookie value has been set, and I need a way to check this.

In my code behind (test.aspx.cs) I have the following line

   Label.Text = Request.Cookies["somecookie"].Value;

This will throw a NullReferenceException if "somecookie" was never set, and from that point on, I can't read any other cookie info.

How can I test whether or not this cookie was set before applying the ".Value" to the cookie object?
1 Solution
Elvio Lujan.Net Senior DeveloperCommented:
if (Request.Cookies["somecookie"] != null)
    Label.Text = Request.Cookies["somecookie"].Value;
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now