在 dotnet webapi 5 中发布文件时出现 405 错误

Getting 405 error when posting a file in dotnet webapi 5

尝试使用 swagger 测试我的 api 时出现 405 错误。我的 api 接受以下格式的数据。

 [HttpPost("AddEmployee")]
  public IActionResult AddEmployee(EmployeeDto employee, IFormFile file )
   {

   }

响应获取

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.13",
  "title": "Unsupported Media Type",
  "status": 415,
  "traceId": "00-19508b3749296a4bb84e43b5d21dc6c7-cabb1ff5b2609a43-00"
}

据我所知,在 asp.net 核心网站 api 中,如果您不设置 [FromForm],它只会接受 json 格式请求。

所以我建议您可以为每个参数设置 [FromForm],如下所示:

[HttpPost("AddEmployee")]
  public IActionResult AddEmployee([FromForm]EmployeeDto employee, [FromForm]IFormFile file )
   {

   }

但是对于swagger来说,如果web api paramaters包含模型和ifromfile,则无法设置正确的参数。

我建议您可以为此 api 方法创建一个新的视图模型,其中包含如下所示的 ifromfile:

public class EmployeeDto
{
    public int Id { get; set; }
    public string Wtest { get; set; }

    public IFormFile file { get; set; }
}

api:

    [HttpPost("AddEmployee")]
    public IActionResult AddEmployee([FromForm]EmployeeDto employee)
    {
        return Ok();
    }