我可以指定 Web-Api 方法需要 Swashbuckle/Swagger 中的文件生成 page/json

Can I specify that Web-Api method expects a file in Swashbuckle/Swagger generated page/json

我得到了一个 Web-Api,它具有以下获取文件的简化方法:

[HttpPut("Test/{id}")]
public IActionResult PutTest(string id)
{
    Stream file = Request.Body;
    //rest of method
    return StatusCode(201);
}

它工作正常,尽管在创建的 SwaggerUI 页面中没有提及在正文中需要文件的方法。有没有办法在生成的 SwaggerUI 页面中指定需要文件的方法?

我可以使用以下代码模拟输入:

var content = new StreamContent(new FileStream("C:\temp\test.txt", FileMode.Open));

using (var client = new HttpClient())
using (var response = client.PutAsync(url, content))
{
    var result = response.Result;
    //more code   
}

文件上传未记录在案,因为它不是操作方法中的参数。 Swagger 无法知道您在操作本身内部正在做什么。尝试以这种方式处理文件上传无论如何都是不好的做法。您可以使用 IFormFile,但仅当您的请求正文编码为 multipart/form-data 时才有效。如果您正在处理 JSON 或基本上任何符合 FromBody 的条件,那么您需要绑定到 byte[]:

[HttpPut("Test/{id}")]
public IActionResult PutTest(string id, byte[] file)
{
    //rest of method
    return StatusCode(201);
}

现在,[ApiController] 属性应用的自动 FromBody 仅适用于 class 类型,所以我不确定它是否适用于一个byte[]。如果没有,就这样做:

public IActionResult PutTest(string id, [FromBody]byte[] file)