Search code examples
c#asp.net-core-webapiasp.net-core-8

ASP.NET Core 8 Web API : pass in an int array to controller method


I'm aware this has been asked elsewhere, but a lot of the questions are very old and stale and .NET has moved on a bit since then so I'm hopeful there is now a simple solution to this other than having to implement a custom model binder...

I have a Web API controller method like this:

[HttpGet("{storeId:int}")]
public async Task<IActionResult> Index(int storeId, int requiredQuantity, [FromQuery] int[] plus)
{
    try
    {
        // lots of incredible things

        return Ok(response);
    }
    catch (Exception ex)
    {
        return StatusCode(500, new { message = "An error occurred while processing your request. Please try again later." });
    }
}

I can invoke this like this:

GET https://localhost:44385/test/test/650?plus=13&plus=4412&plus=4099&requiredQuantity=41

However I need to be able to invoke it like that:

GET https://localhost:44385/test/test/650?plus=13,4412,4099&requiredQuantity=41

Is this possible in a close to native way without having to write a full custom model binder, or pass in a string and convert to an int array?


Solution

  • You could implement custom modelbinder to achieve.

        public class CommaSeparatedBinder : IModelBinder
        {
            public Task BindModelAsync(ModelBindingContext bindingContext)
            {
                var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
                var stringArray = valueProviderResult.FirstValue?.Split(',')?? Array.Empty<string>();
                int[] intArray = Array.ConvertAll(stringArray, s => int.TryParse(s, out int result) ? result : 0);
                bindingContext.Result = ModelBindingResult.Success(intArray);
                return Task.CompletedTask;
            }
        }
    

    Then add this custom binder

    public async Task<IActionResult> Index(int storeId, int requiredQuantity, [FromQuery][ModelBinder(typeof(CommaSeparatedBinder))] int[] plus)
    

    Test result
    enter image description here