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]);
}
}
The value of Request. QueryString(parameter) is an array of all of the values of parameter that occur in QUERY_STRING. You can determine the number of values of a parameter by calling Request. QueryString(parameter).
Key duplication refers to the process of creating a key (lock) based on an existing 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With