开发者

What's the best way to check for duplicate keys in Querystring/Post/Get requests

I'm writing a small API and need to check for duplicate keys in requests. Could someone recommend the best way to check for duplicate keys. I'm aware I could check the key.Value for commas in the开发者_开发百科 string, but then I have another problem of not allowing commas in API requests.

    //Does not compile- just for illustration
    private void convertQueryStringToDictionary(HttpContext context)
    {
       queryDict = new Dictionary<string, string>();
        foreach (string key in context.Request.QueryString.Keys)
        {
            if (key.Count() > 0)  //Error here- How do I check for multiple values?
            {       
                context.Response.Write(string.Format("Uh-oh"));
            }
            queryDict.Add(key, context.Request.QueryString[key]);
        }       
    }


QueryString is a NameValueCollection, which explains why duplicate key values appear as a comma separated list (from the documentation for the Add method):

If the specified key already exists in the target NameValueCollection instance, the specified value is added to the existing comma-separated list of values in the form "value1,value2,value3".

So, for example, given this query string: q1=v1&q2=v2,v2&q3=v3&q1=v4, iterating through the keys and checking the values will show:

Key: q1  Value:v1,v4 
Key: q2  Value:v2,v2 
Key: q3  Value:v3

Since you want to allow for commas in query string values, you can use the GetValues method, which will return a string array containing the value(s) for the key in the query string.

static void Main(string[] args)
{
    HttpRequest request = new HttpRequest("", "http://www.stackoverflow.com", "q1=v1&q2=v2,v2&q3=v3&q1=v4");

    var queryString = request.QueryString;

    foreach (string k in queryString.Keys)
    {
        Console.WriteLine(k);
        int times = queryString.GetValues(k).Length;
        if (times > 1)
        {
            Console.WriteLine("Key {0} appears {1} times.", k, times);
        }
    }

    Console.ReadLine();
}

outputs the following to the console:

q1
Key q1 appears 2 times.
q2
q3
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜