将Angular FormData中的int列表发送到C#中的POST Web API [英] Send list of int in Angular FormData to POST Web API in C#

查看:53
本文介绍了将Angular FormData中的int列表发送到C#中的POST Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to send a list of integers inside an object to a POST API in C#. This is what I am doing:

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:

The following is the 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中收到以下错误:

I am getting the following error from the Web API:

{"Ids":[值'[5,6,7]'无效."]}

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

我该如何实现?我想在 MyModel 中将 Ids 的类型保留为 List< int> int [] (直接发送)服务器中没有JSON解析的ID).

How do I achieve this? I want to keep the type of Ids in MyModel as List<int> or int[] (directly send the Ids without JSON parsing in the server).

推荐答案

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

In order to allow ASP.NET Core model binder to bind an array you need to add array values multiple times with the same parameter name

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

这篇关于将Angular FormData中的int列表发送到C#中的POST Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆