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

标签 c# asp.net-core-webapi

我正在尝试将列表参数传递给 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/

相关文章:

c# - 已启用的组合框控件在 Windows 10 中看起来已禁用?

c# - 无法理解 LINQ 扩展方法

c# - ASP.NET Core 单元测试在测试 Controller 问题响应时抛出 Null Exception

asp.net - 无法使用 HTTPS 启动 ASP.NET Core

c# - 在 C# 中,我可以阻止对象从终结器中被垃圾收集吗?

c# - 为什么我的命令不能启用按钮?

c# - IronPython - "AttributeError: object has no attribute"自定义类

Azure .NET API 和文件上传

asp.net-core - 读取请求正文两次

c# - 当 Controller 位于另一个项目中时,Get 方法不返回值