0

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

1
  • Note that passing duplicate query parameters isn't supported by a lot of webservers. Commented Mar 15, 2024 at 17:30

2 Answers 2

0

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.