如何在angular6和ASP.NET Core 2 WebAPI中使用TypeScript模型发布FormData

时间:2019-06-26 19:52:22

标签: c# angular6 asp.net-web-api2 asp.net-core-2.2

我在asp.net core 2 Web API中具有以下模型:

public class MainVM
{
        public int ID { get; set; }
        public string Name { get; set; }
        public bool IsActive { get; set; }
        public int DepartmentID { get; set; }
        public IFormFile Logo { get; set; }
        public List<ChildVM> ListChilds { get; set; }

}

public class ChildVM
{
        public string Name { get; set; }
        public int SequenceNo { get; set; }
        public int NoOfPrices { get; set; }
        public IFormFile Image { get; set; }
}

和端点:

[HttpPost]
[Consumes("multipart/form-data")]
public void Post([FromForm]MainVM data)
{
}

我用于从angular发布数据的Angular6服务:

addData(mydata: MainVM, logo: File, myImages: File[]): Observable<MainVM> {

    const formData: FormData = new FormData();
    formData.append('Logo', logo, logo.name);
    if (myImages && myImages.length > 0) {
      for (var i = 0; i < myImages.length; i++) {
        formData.append('ListChilds[].Image', myImages[i], myImages[i].name);
      }
    }
    formData.append('data', new Blob([JSON.stringify(mydata)], { type: 'application/json' }));

    console.log(formData);
    return this.http.post<MainVM>('http://localhost:60458/api/mycontroller/', formData, httpOptions).pipe(
      map((res) => { console.log('res'); return res; }),
      catchError(this.handleError('lpc', null))
    );
  }

现在我面临的问题是它仅在Web api上收到徽标,所有其他字段保持为空。

我想我缺少了一些东西。请引导我。

谢谢。

1 个答案:

答案 0 :(得分:0)

最后,我找到了解决方案: 首先,我更改了模型,从ChildVM中删除了以下行:

public IFormFile Image { get; set; }

并在MainVM中添加以下行:

public List<IFormFile> ListImages{ get; set; }

之所以这样做,是因为我发现Asp.net Core 2.2中存在一些错误,如果我们在子模型中采用IFormFile类型,Asp.net Core 2.2将开始挂起(详细信息在下面的链接中):

  

https://github.com/aspnet/AspNetCore/issues/4802

现在在客户端,我相应地更改了模型,服务的更改如下:

addData(mydata: MainVM, logo: File, myImages: File[]): Observable<MainVM> {

  const formData: FormData = new FormData();
  formData.append('Logo', logo, logo.name);
  this.buildFormData(formData, mydata, null);
  if (myImages && myImages.length > 0) {
    for (var i = 0; i < myImages.length; i++) {
      formData.append('ListImages', myImages[i], myImages[i].name);
    }
  }
 console.log(formData);
 return this.http.post<MainVM>('http://localhost:60458/api/mycontroller/', formData, httpOptions).pipe(
  map((res) => { console.log('res'); return res; }),
  catchError(this.handleError('lpc', null))
 );
}

buildFormData(formData, data, parentKey) {
  if (data && typeof data === 'object' && !(data instanceof Date) && !(data instanceof File)) {
   Object.keys(data).forEach(key => {
     console.log(key);
     this.buildFormData(formData, data[key], parentKey ? `${parentKey}[${key}]` : key);
   });
 } 
 else {
     const value = data == null ? '' : data;

     formData.append(parentKey, value);
  }
 }