Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse a query string with "&" in the value using C#?

I have a C# custom webpart on a sharepoint 2007 page. When clicking on a link in an SSRS report on another page, it sends the user to my custom webpart page with a query string like the following:

?tax4Elem=Docks%20&%20Chargers&ss=EU%20MOVEX&Phase=1&tax3Elem=Play%20IT&tax5Elem=Charger

Take note of the value for "tax4Elem", which is basically "Docks & Chargers". (The ampersand can actually come up in "tax4Elem", "tax3Elem", and "tax5Elem").

I cannot have the ampersand in that value encoded so I will have to work with this.

How do I parse this query string so that it doesn't recognize the "&" in "Docks & Chargers" as the beginning of a key/value pair?

Thanks in Advance! kate

like image 919
KateF Avatar asked Nov 05 '22 13:11

KateF


2 Answers

If you really cannot correct the URL, you can still try to parse it, but you have to make some decisions. For example:

  • Keys can only contain alphanumeric characters.
  • There are no empty values, or at least, there is always an equal sign = after the key
  • Values may contain additional ampersands and question marks.
  • Values may contain additional equal signs, as long as they don't appear to be part of a new key/value pair (they are not preceded with &\w+)

One possible way to capture these pairs is:

MatchCollection matches = Regex.Matches(s, @"\G[?&](?<Key>\w+)=(?<Value>.*?(?=$|&\w+=))");
var values = matches.Cast<Match>()
                    .ToDictionary(m => m.Groups["Key"].Value,
                                  m => HttpUtility.UrlDecode(m.Groups["Value"].Value),
                                  StringComparer.OrdinalIgnoreCase);

You can then get the values:

string tax4 = values["tax4Elem"];

Note that if the query string is "invalid" according to our rule, the pattern may not capture all values.

like image 148
Kobi Avatar answered Nov 09 '22 08:11

Kobi


I think you can't parse that string correctly - it has been incorrectly encoded. The ampersand in "Docks & Chargers" should have been encoded as %26 instead of &:

?tax4Elem=Docks%20%26%20Chargers&ss=EU%20MOVEX&Phase=1&tax3Elem=Play%20IT&tax5Elem=Charger

Is it possible to change the code that generated the URL?

like image 30
Mark Byers Avatar answered Nov 09 '22 08:11

Mark Byers