Usings Net 6 Minimal API I have the following route:
builder.MapGet("posts", async ([FromQuery] IEnumerable<Int32> postsIds) => {
});
The parameters postsIds
contains the ids
of posts to be loaded, e.g., "1, 3, 5".
I get the following error when running the application:
Exception thrown: 'System.InvalidOperationException' in Microsoft.AspNetCore.Http.Extensions.dll: 'No public static bool IEnumerable.TryParse(string, out IEnumerable) method found for postsIds.
So I created the following:
public class CommaSeparatedValues<T> {
public IEnumerable<T> Values { get; set; } = new List<T>();
public static Boolean TryParse(String? value, IFormatProvider? provider, out CommaSeparatedValues<T>? commaSeparatedValues) {
IEnumerable<T>? values = value?.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Cast<T>();
if (values is null) {
commaSeparatedValues = null;
return false;
}
commaSeparatedValues = new CommaSeparatedValues<T> { Values = values };
return true;
}
And changed the endpoint to:
builder.MapGet("posts", async ([FromQuery] CommaSeparatedValues<Int32> postsIds) => {
});
Does this make sense? Can I improve / simplify this approach? Or this is the way?