【问题标题】:Send list of int in Angular FormData to POST Web API in C#将 Angular FormData 中的 int 列表发送到 C# 中的 POST Web API
【发布时间】:2019-12-03 09:13:41
【问题描述】:

我想将对象内的整数列表发送到 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":["值 '[5,6,7]' 无效。"]}

我如何实现这一目标?我想将MyModelIds 的类型保留为List&lt;int&gt;int[](直接发送ID,而不在服务器中解析JSON)。

【问题讨论】:

    标签: c# asp.net angular asp.net-core


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      如果不需要具有 id 列表的字段,则处理空值的唯一方法(对我有用)根本不附加到 formData。我还通过 Number(id) > 0 在 Ids 数组中排除 0、""、nullundefined

      if (Array.isArray(Ids)) {
        Ids.forEach(
          (id: string) => Number(id) > 0 && formData.append('Ids', id),
        );
      }
      

      【讨论】:

        【解决方案3】:

        .Net core post方法

        public ActionResult<MyModel> Post([FromBody]long[] ids)
        {
        .............
        }
        

        角柱法

        post(ids:number[]): Observable<MyModel> {
        let body = JSON.stringify(ids);
        const httpOptions = {
            headers: new HttpHeaders({
                'Content-Type':  'application/json'
            })
         };
         return this.httpclint.post<MyModel>(yourApiUrl, body, httpOptions)
            .pipe(
             catchError(this.handleError)
            );  
        }
        

        【讨论】:

          猜你喜欢
          • 2018-08-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多