1

I have Web API endpoint which expects a list of enum values. I am using HttpUtility.ParseQueryString to generate the query string where I want to pass multiple key-value pair in the query string as below,

../api/getdata?myEnum=One&myEnum=Two&myEnum=Three

But, the ParseQueryString is creating the query string url as below,

../api/getdata?myEnum=One%2cTwo%2cThree

Here is my code,

var queryString = System.Web.HttpUtility.ParseQueryString(string.Empty);
queryString.Add("myEnum", "One");
queryString.Add("myEnum", "Two");
queryString.Add("myEnum", "Three");

How can I create the expected query string url with duplicate keys.

../api/getdata?myEnum=One&myEnum=Two&myEnum=Three
Charan Ghate
  • 1,384
  • 15
  • 32
  • 3
    ParseQueryString string returns a NameValueCollection which cannot have duplicate records per key, so the value will be "One,Two,Three". you can always write a custom method that will split the value and returns it the way you want. I'm not sure why you need to send the same parameters and can't just split the value on the other side (if you have access of course) – vhr Sep 17 '19 at 11:44
  • 1
    Unfortunately [there is no standard](https://stackoverflow.com/q/1746507/4137916) as to how to send multiple values, and .NET has largely settled on using `NameValueCollection` everywhere, meaning it almost necessarily uses the comma-separation method. You'd think it's an easy matter of then building the query string manually, so easy that there must be simple ways in the framework of doing so with proper encoding, but [you'd be mistaken](https://stackoverflow.com/q/829080/4137916). – Jeroen Mostert Sep 17 '19 at 11:49

2 Answers2

1

You can achieve the expected result via the AddQueryString method of the QueryHelpers class in ASP.NET Core.

This class is contained in the Microsoft.AspNetCore.WebUtilities NuGet package.

string url = "http://yourservice/api/getdata";

url = QueryHelpers.AddQueryString(url, "myEnum", "One");
url = QueryHelpers.AddQueryString(url, "myEnum", "Two");
url = QueryHelpers.AddQueryString(url, "myEnum", "Three");

Console.WriteLine(url); // http://yourservice/api/getdata?myEnum=One&myEnum=Two&myEnum=Three
pfx
  • 20,323
  • 43
  • 37
  • 57
0

This feature has been added a while back [0] using QueryBuilder.

You can now use query builder and pass in an IEnumerable. So if I wanted to add a bunch of id=something parameters to a query I can do this:

var query = new QueryBuilder {{"id", itemIds}}.ToQueryString();

This will give me a query string in the form: ?id=1&id=2&id=...

In your particular case it would be something like this if you had an IEnumerable of your enums.

var query = new QueryBuilder {{"myEnum", myEnums}}.ToQueryString();

[0] https://github.com/dotnet/aspnetcore/issues/7945

span
  • 5,405
  • 9
  • 57
  • 115