【问题标题】:Getting 405 error when posting a file in dotnet webapi 5在 dotnet webapi 5 中发布文件时出现 405 错误
【发布时间】:2021-06-15 18:31:32
【问题描述】:

尝试使用 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"
}

【问题讨论】:

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


    【解决方案1】:

    据我所知,在asp.net core web api中如果不设置[FromForm],它只会接受json格式的请求。

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

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

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

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

    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();
        }
    

    【讨论】:

      猜你喜欢
      • 2015-11-14
      • 2014-01-10
      • 2015-06-27
      • 2013-11-04
      • 1970-01-01
      • 1970-01-01
      • 2019-09-05
      • 2016-10-16
      • 2017-05-02
      相关资源
      最近更新 更多