[英]C# / ASP.NET Core Web API : how to pass a list parameter?
我正在嘗試將列表參數傳遞給 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 發布請求失敗並出現以下錯誤:
JSON 值無法轉換為 System.String[]。 路徑:$ | 行號:0 | 字節位置內線:1。
這是請求:
{
"CustomerNumbers": ["test"],
"OrderDateFrom": "2021-01-01",
"OrderDateTo": "2021-11-02"
}
我也嘗試了List<string>
,而不是使用字符串數組。 我得到了同樣的錯誤。
知道為什么框架不了解如何接收列表嗎?
由於您的參數名稱,我想您的數組看起來像這樣[2, 3, 5]
但應該看起來像這樣["2", "3", "5"]
。 它需要一個字符串數組,而不是一個 int 數組。 否則將數據類型更改為int[] CustomerNumbers
您應該創建一個 class 並使用此 class 接收 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)
{
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.