Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correct parse query string in C# if value contains ampersand? [duplicate]

Tags:

c#

I need parse query string: ?artist=singer1 & singer2&song=name song

Static method HttpUtility.ParseQueryString doesn't work the way I want if value contains ampersand like "singer1 & singer2".

For example:

string qs = "?artist=singer1 & singer2&song=name song"; 
NameValueCollection query = HttpUtility.ParseQueryString(qs);

Result is:

  1. artist = singer1
  2. null = singer2
  3. song = name song

I would like result

artist = singer 1 & singer2
song = name song

Any idea?

like image 848
misak Avatar asked Oct 15 '25 03:10

misak


2 Answers

The ampersand (&) in the middle of one of your values is throwing off the parser since it's a reserved symbol. Replace it with its numeric code instead:

string qs = "?artist=singer1+%26+singer2&song=name song"; 
NameValueCollection query = HttpUtility.ParseQueryString(qs);
like image 57
D Stanley Avatar answered Oct 17 '25 15:10

D Stanley


Your problem is that & carries special meaning in a query string, namely to separate arguments. The & in the middle of your perceived artist parameter is actually being parsed as an argument separator. You need to URL encode the & when constructing the URL.

For example, one correct query string would be:

?artist=singer1+%26+singer2&song=name+song

(Spaces can usually be encoded either as + or %20, but that's a topic for another discussion.)

You can use HttpUtility.UrlEncode() when building the query string components to ensure that the result is correctly escaped. For example, you could build the query string like this:

static void Main()
{
    var values = new NameValueCollection();
    values["artist"] = "singer1 & singer2";
    values["song"] = "name song";

    Console.WriteLine(CreateQueryString(values));
}

static string CreateQueryString(NameValueCollection values)
{
    if (values == null) { throw new ArgumentNullException("values"); }

    return string.Join(
        "&",
        values.AllKeys.Select(key => HttpUtility.UrlEncode(key) + "=" +
                                     HttpUtility.UrlEncode(values[key]))
                      .ToArray());
}

In other words, the issue is occuring at the time you build the query string, not when you are trying to parse it. When parsing it you already have a semantically incorrect query string; there's nothing you can do at this point.

like image 33
cdhowie Avatar answered Oct 17 '25 16:10

cdhowie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!