Home > database >  C# / ASP.NET Core Web API : how to pass a list parameter?
C# / ASP.NET Core Web API : how to pass a list parameter?

Time:12-31

I'm trying to pass a list parameter to an ASP.NET Core 5 Web API.

Here is my endpoint:

[ApiController]
[Route("[controller]")]
public class InvoiceController : ControllerBase
{
    private readonly IConfiguration _configuration;

    public InvoiceController(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    [HttpPost]
    public List<CustomerInvoice> Post(string[] CustomerNumbers, DateTime OrderDateFrom, DateTime OrderDateTo)
    {
    }
}

Sending json post request fails with this error:

The JSON value could not be converted to System.String[]. Path: $ | LineNumber: 0 | BytePositionInLine: 1.

and here is the request:

{
    "CustomerNumbers": ["test"],
    "OrderDateFrom": "2021-01-01",
    "OrderDateTo": "2021-11-02"
}

Instead of using a string array, I also tried List<string>. I got the same error.

Any idea why the framework does not understand how to receive a list?

CodePudding user response:

You should create a class and receive JSON with this class. This may solve your problem.

public class ClassExample
{
    public List<string> CustomerNumbers { get; set; }
    public DateTime OrderDateFrom { get; set; }
    public DateTime OrderDateTo { get; set; }
}



[HttpPost]
public List<CustomerInvoice> Post(ClassExample requestParameter)
{
}
  • Related