gpt4 book ai didi

c# - 将 Angular FormData 中的 int 列表发送到 C# 中的 POST Web API

转载 作者:行者123 更新时间:2023-12-05 02:10:10 24 4
gpt4 key购买 nike

我想将对象内的整数列表发送到 C# 中的 POST API。这就是我正在做的:

const headers = new HttpHeaders().append(
"Content-Disposition",
"multipart/form-data"
);

let formData: FormData = new FormData();
formData.append("name", "name");
formData.append("Ids", JSON.stringify(Ids));
return this._http.post(
`${environment.baseUrl}${this.companyApiUrl}`,
formData,
{ headers: headers }
);

在哪里Ids类型为 number[] .

以下是 C# WebAPI:

public ActionResult<MyModel> Post([FromForm] MyModel model)
{
...
}

MyModel :

public class MyModel
{
public string Name { get; set; }
public List<int> Ids { get; set; } // I have also tried int[]
}

我从 Web API 收到以下错误:

{"Ids":["The value '[5,6,7]' is not valid."]}

我如何实现这一点?我想保留 Ids 的类型在MyModel作为List<int>int[] (服务器端不做JSON解析,直接发送Id)。

最佳答案

为了允许 ASP.NET Core 模型绑定(bind)器绑定(bind)数组,您需要使用相同的参数名称多次添加数组值

let formData: FormData = new FormData();
formData.append("name", "name");
for(let i = 0; i < Ids.length; i++) {
formData.append("Ids", Ids[i]);
}

关于c# - 将 Angular FormData 中的 int 列表发送到 C# 中的 POST Web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59153634/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com