在ASP.NET Core WEB API中同时发布图像和正文数据

问题描述

我正在尝试使用ASP.NET Core来发布图像文件和一组参数。是否有任何选项/解决方案可以在POST API中同时发送模型数据和图像。这是POSTMAN中的POST API图像:

enter image description here

以下是带有型号信息的车身:

enter image description here

如果我像下面的代码那样操作,那么我的companyInfo数据为null,并且图像在那里。

    [HttpPost("Post@R_322_4045@ion")]
    public async Task<ActionResult<Company>> PostemployeeJobCategories(IFormFile image,[FromForm]Company companyInfo)
    {
    }

如果我像下面的代码那样执行操作,那么我将获得不受支持媒体类型

    [HttpPost("Post@R_322_4045@ion")]
    public async Task<ActionResult<Company>> PostemployeeJobCategories([FromForm]IFormFile image,[FromBody]Company companyInfo)
    {
    }

任何建议,如何实现目标?

谢谢

解决方法

添加[FromForm]属性并通过Postman中的“表单数据”选项卡发送所有内容对我来说是有效的:

public class OtherData
{
    public string FirstString { get; set; }
    public string SecondString { get; set; }
}
public async Task<IActionResult> Post(IFormFile file,[FromForm]OtherData otherData)
{
     return Ok();
}

postman view

正如vahid tajari指出的那样,您还可以将IFormFile添加到类定义中。

,

在asp.net核心中,您可以一起发送文件和数据,因此请将模型更改为:

 public class Company
    {
        public IFormFile Image { get; set; }
        public string NameEn { get; set; }
        public string Address { get; set; }
        //......
    }

以及您的操作方法:

[HttpPost("PostInformation")]
public async Task<ActionResult<Company>>PostEmployeeJobCategories([FromForm] Company companyInfo)
      {
      }