How to extract specific-case fields from HttpUtility.ParseQueryString?

269 Views Asked by At

The .net standard library function System.Web.HttpUtility.ParseQueryString parses a query string into name/value pairs.

var a = HttpUtility.ParseQueryString("abc=123&def=456");
var x = a["abc"]; /* "123" */

When there are two fields with the same names except they differ by case, the returned object combines both values together with a comma.

var a = HttpUtility.ParseQueryString("abc=123&ABC=456");
var x = a["abc"]; /* "123,456" */

How can I pull out just the "abc" part on its own? Hopefully without rewriting the parser or pre-processing the string.

2

There are 2 best solutions below

0
Tech_learner On BEST ANSWER

Having two keys with same names with different case is not possible with parseQuerystring as its return type is NameValueCollection whose default behavior is to provide a collection of unique keys and if you try to add same key in this collection it will by default add is at comma separated with existing key value .

Let me know if this helps.

0
Adrian Ilie On

Hopefully without rewriting the parser or pre-processing the string.

I don't think it's possible, but here's a somewhat concise implementation that should do the trick:

string pattern = @"(?<=^|&)(\w+)(?==)=(\w+)(?=&?)";
string input = @"abc=123&ABC=456&abc=789";

Dictionary<string, string> parameters = new Dictionary<string, string>();

foreach (Match m in Regex.Matches(input, pattern))
{
    if (parameters.ContainsKey(m.Groups[1].Value))
    {
        //preserve original behaviour, i.e. concat values of same parameters
        parameters[m.Groups[1].Value] = parameters[m.Groups[1].Value] + "," + m.Groups[2].Value;
    } else
    {
        parameters.Add(m.Groups[1].Value, m.Groups[2].Value);
    }
}

This might fail with Unicode parameters outside of a-zA-Z0-9_ so you might have to edit the regex to fit your needs.