Request.Cookies[][] exceptions

  • Thread starter Thread starter Brett Robichaud
  • Start date Start date
B

Brett Robichaud

When I check for a cookie in C# with this type of syntax:

string sID = Request.Cookies["User"]["ID"];

an exception is thrown if the cookie doesn't exist. Is there any way around
that, or some way to see if the cookie exists beforehand?

I need to load a dozen or so cookies, some of which will not exist, and
using a try/catch block makes this difficult if it could fail on any of
them.

-Brett-
 
Hi Brett,

Thanks for posting in the community!
Based on your description, you found that when you use the following code
to retrieve certain cookie item from Request.Cookies Collection,

string sID = Request.Cookies["User"]["ID"];

you'll get exception if the cookie item not exist. So you wonder the proper
way to retrieve cookie item and check whether it exists, yes?

As for this problem, I think you can check whether the parent key item
exists, if exist, then retrieve the sub key item. For example:

if(Request.Cookies["mainkey"] != null)
{
string val = Request.Cookies["mainkey"]["subkey"];
.....
}

This is the certain code style in MSDN, and here is the certain tech
articles on ASP.NET COOKIE in MSDN:
#Basics of Cookies in ASP.NET
http://msdn.microsoft.com/library/en-us/dv_vstechart/html/vbtchASPNETCookies
101.asp?frame=true#vbtchaspnetcookies101anchor8

Hope this helps.



Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Get Preview at ASP.NET whidbey
http://msdn.microsoft.com/asp.net/whidbey/default.aspx
 
Ah, that makes sense. I wasn't checking to see if the parent key existed.
I guess it never occurred to me that an exception would be thrown when
trying to check for a subkey but not when checking the parent.

Excellent. Solved my problem. Thanks.

-Brett-
 
Back
Top