I have an issue in ASP.Net when trying to interrogate the query string for values when the parameter name is the same, and the values of that parameter contains commas.
For Instance, suppose I have a URL that reads as follows...
https://example.com/mypage.aspx?val=red%2cblue&val=black%2cwhite
As you can see, this URL has 2 querystring parameters both called "val", and the values for each have commas that have been URL encoded, but when I interrogate the query string parameter "val" in c#, I get an array of 4 separate items (red, blue, black and white) when what I actually need to get are the 2 values ("red,blue" and "black,white")
When reading the values in C# it seems the URL encoding is "helpfully" decoded, which in turn is causing me an issue in that I cant accurately define the values of my parameters. I'd normally read the querystring parameter, and perform a split on the comma, but this approach isnt working for me.
To complicate matters, I have no way of knowing how many commas can appear in my values, or how many values are being included. All the URLs below could be returned for example...
https://example.com/mypage.aspx
https://example.com/mypage.aspx?val=red%2cblue
https://example.com/mypage.aspx?val=red%2cblue&val=black%2cwhite&val=red%2cblue%2cgreen
https://example.com/mypage.aspx?val=red%2cblue&val=black%2cwhite&val=yellow
Is there a simple way in C# to correctly interpret the query string values?
I would say that having multiple keys with the same name in query string is not a very good idea due to absense of defined standard.
Though it seems that HttpUtility.ParseQueryString
can handle this scenario in a way that you need:
var nameValueCollection = HttpUtility.ParseQueryString("val=red%2cblue&val=black%2cwhite");
var result = nameValueCollection.GetValues("val");
foreach (var s in result)
{
Console.WriteLine(s); // prints 2 strings: "red,blue" and "black,white"
}