我正在尝试将列表参数传递给 ASP.NET Core 5 Web API。
这是我的端点:
[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)
{
}
}
发送 json post 请求失败并出现以下错误:
The JSON value could not be converted to System.String[]. Path: $ | LineNumber: 0 | BytePositionInLine: 1.
这是请求:
{
"CustomerNumbers": ["test"],
"OrderDateFrom": "2021-01-01",
"OrderDateTo": "2021-11-02"
}
我没有使用字符串数组,而是尝试了 List<string>
。我也遇到同样的错误。
知道为什么框架不理解如何接收列表吗?
最佳答案
您应该创建一个类并通过该类接收 JSON。这可能会解决您的问题。
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)
{
}
关于C#/ASP.NET Core Web API : how to pass a list parameter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70536315/