I have quite a few places where multidimensional arrays of varying lengths are used as query parameters.
With controllers a request with to /multi?vals[0][0]=5&vals[0][1]=6&vals[1][0]=6&vals[1][1]=7
binds without issues.
[Route("/multi")]
public class MultiController : Controller
{
[HttpGet("")]
public IActionResult Index([FromQuery] int[][] vals)
{
return this.Ok(string.Join(" ", vals.Select(x => string.Join(":", x))));
}
}
With Minimal APIs,
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
app.MapGet("/multi-minimal", ([FromQuery] int[][] vals) => $"Hello World! {string.Join(":::", vals.Select(x => string.Join(":", x)))}");
app.MapControllers();
app.Run();
}
}
There is an error trying to map the route
InvalidOperationException: No public static bool int[].TryParse(string, out int[]) method found for vals.
Microsoft.AspNetCore.Http.RequestDelegateFactory.BindParameterFromValue(ParameterInfo parameter, Expression valueExpression, RequestDelegateFactoryContext factoryContext, string source)
I don't see how its possible to register a static TryParse method on an int[].
I have seen some documentation around BindAsync
for scenarios like the following:
public class Dto
{
[BindProperty(Name = "coordinates")]
public int[][] Coordinates { get; set; }
[BindProperty(Name = "a")]
public string? PropA { get; set; }
[BindProperty(Name = "b")]
public string PropB { get; set; }
// lots more properties
public static ValueTask<Dto?> BindAsync(HttpContext context)
{
throw new NotImplementedException();
}
}
But for larger DTOs it's a tad inconvenient to have to parse the entire query string and set properties that are already supported. This seemed more targeted at 'complex types' but in my case its more 'complex primitives' I am trying to bind.
Any suggestions on how to get app.MapGet("/multi-minimal", ([FromQuery] int[][] vals) => {}");
working with varying size multidimensional arrays would be greatly appreciated.