views:

392

answers:

2

Hi, I set cookies based on the referral links and they all start with the same letters, lets say "google", but they end with _xxx, _yyy, _zzz or whatever is the reference.

Now, when I try to get the cookies later, I have the problem that I don't want to check for all of the different cookies, I would like to check for all cookies that start with "google" and based on that I will start a script that goes on with processing.

if (Request.Cookies("google"))
{
    run other stuff
}

Any idea how I can add StartWith or something to it? I am a newbie, so not really that into C# yet.

Thanks in advance,

Pat

+2  A: 

You have to check all the cookies if you want to find ones with a certain suffix (Randolpho's answer will work).

It's not a particularly good idea to do it that way. The problem is that the more cookies you create, the more overhead you put on the server and connection. Say you have 10 cookies: google_aaa, google_bbb, etc. Each request will send all 10 cookies to your server (this includes requests for images, css, etc.

You're better off using a single cookie which is some sort of key to all the information stored on your server. Something like this:

var cookie = Cookies["google"];
if(cookie!=null)
{
    // cookie.Value is a unique key for this user. Lookup this 
    // key in your database or other store to find out the 
    // information about this user.
}
Keltex
I agree. My answer provides a solution to the immediate problem, but a better way should probably be sought.
Randolpho
A: 

Well.. HttpRequest.Cookies is a collection. So use LINQ:

var qry = from cookieName in Request.Cookies.Keys
          where cookieName.StartsWith("google")
          select cookieName;

foreach(var item in qry)
{
   // get the cookie and deal with it.
   var cookie = Request.Cookies[item];
}

Bottom line: you can't get away from iterating over the entire cookie collection. But you can do it easily using LINQ.

Randolpho