Add a list of enum values to a query parameter

49 views Asked by At

For example you have this enum :

 public enum MyEnum
 {
     enum1,
     enum2,
     enum3,
     enum4
 }

And you want to pass a IEnumerable<MyEnum> as a query parameter?

I tried this :

 var queryParameters = new Dictionary<string, string>();

 var myEnums = someParemeters.MyEnums.Select(x => new KeyValuePair<string, string>(nameof(MyEnum), x.ToString()));

queryParameters.Add(nameof(SomeParemeters.MyEnums), myEnums.ToString());

if (queryParameters != null) uri = QueryHelpers.AddQueryString(uri, queryParameters);

But this doesn't work off course. How can I get the MyEnums as a string to send as query parameter '?myEnums=enum1&myEnums=enum4'?

PS : I'm using the library Microsoft.AspNetCore.WebUtilities

2

There are 2 answers

0
RezaNoei On

Look at following example:

public enum Season
{
    Spring = 1, 
    Summer = 2, 
    Fall = 3,
    Winter = 4
}

[HttpGet]
public string Get([FromQuery] Season[] seasons)
{
    return string.Join(", ", seasons.Select(s => s.ToString()));
}

you can simple call this method by:

https://[RestApiEndpoint]/WeatherForecast?seasons=1&seasons=2

If you gonna get these values as Strings not numeric literals you can read following question:

ASP.NET MVC Core API Serialize Enums to String

0
r-parra On

You can loop for each value of the enum and then join the elements using the character desired.

Something like this:

var enumList = Enum.GetValues(typeof(MyEnum)).OfType<MyEnum>().Select(x => nameof(MyEnum) + "=" + x.ToString()).ToList();
string enumListStr = string.Join("&", enumList);

Hope it helps.