【问题标题】:How to get a upload button in swagger for IFormFile combined with other properties?如何在 IFormFile 与其他属性相结合的情况下大张旗鼓地获取上传按钮?
【发布时间】:2022-01-12 10:53:04
【问题描述】:

我创建了一个带有 Swagger 的 Asp.net core 3.1 web api,用于将文件上传到服务器。以下代码工作正常:

    [HttpPost("PostFile")]
    public ActionResult PostFile(IFormFile uploadedFile)
    {            
        var saveFilePath = Path.Combine("c:\\savefilepath\\", uploadedFile.FileName);
        using (var stream = new FileStream(saveFilePath, FileMode.Create))
        {
            uploadedFile.CopyToAsync(stream);
        }
        return Ok();
    }

当我尝试运行它时,我会在 swagger 中获得一个不错的上传按钮。

但是,现在我想使用不同的模型。它与 IFormFile 一起具有更多属性。

public class FileUploadRequest
{
    public string UploaderName { get; set; }
    public string UploaderAddress { get; set; }
    public IFormFile File { get; set; }
}

当我尝试使用此模型时,我在 Swagger 中看不到任何可以帮助我在请求中附加文件的上传按钮。

由于某种原因,它将 IFormFile 显示为字符串。如何在此处获得上传按钮?

【问题讨论】:

    标签: rest asp.net-core swagger asp.net-core-webapi


    【解决方案1】:

    在 ASP.NET Core Web API 中,默认绑定application/json 格式数据。但是你的模型需要的是multipart/form-data 类型的数据。所以你需要[FromForm]属性来指定来源。

    我在 ASP.NET Core 3.1 中使用Swashbuckle.AspNetCore 版本5.6.3

    [HttpPost]
    public ActionResult PostFile([FromForm]FileUploadRequest model)
    {
    
    }
    

    结果:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-18
      • 2010-09-13
      • 2017-10-30
      • 1970-01-01
      • 2016-07-05
      • 1970-01-01
      相关资源
      最近更新 更多