如何通过文件将其他参数从 Angular 传递到 ASP.NET 核心控制器?

How to pass other parameter with file to ASP.NET Core controller from Angular?

我有问题,我需要传递模型作为第一个参数,作为第二个参数,我需要传递一个文件

正在将文件添加到表单:

const formDate = new FormData();
formDate.append("File", this.file);

从angular发送数据:

this.dataService.createRestaurant(this.restaurant, formDate)
    .subscribe((data: Restaurant) => this.loadProducts(data))

数据发送服务:

createRestaurant(model: Restaurant, form: FormData){
  const headers = new HttpHeaders().append("Content-Disposition", "multipart/form-data")
    return this.http.post(this.url, {model, form}, {headers: headers});
  }

Asp.net 核心中的控制器:

public IActionResult Post(Restaurant restaurant, IFormFile File)
    {
       code...
    }

我试了两天解决这个问题,模型传输正常,但是文件一直是null

尝试将您的操作更改为:

public IActionResult Post(RestaurantViewModel viewModel)
    {
       code...
    }

通过创建 ViewModel

public RestaurantViewModel
{
public Restaurant restaurant {get; set;}
public IFormFile File {get; set;}
}

这就是将数据塑造成表格的方式

const formDate = new FormData();
formDate.append("restaurant", JSON.stringify(this.restaurant));
formDate.append("file", this.file[0], this.file[0].name);

"this.restaurant" 与 Asp.Net Core

中的数据模型完全相同

接受 json 数据,如本题所示: ASP.NET Core and formdata binding with file and json property