[英]Can I specify that Web-Api method expects a file in Swashbuckle/Swagger generated page/json
I got a Web-Api with the following simplified method for obtaining a file:我得到了一个 Web-Api,使用以下简化的方法来获取文件:
[HttpPut("Test/{id}")]
public IActionResult PutTest(string id)
{
Stream file = Request.Body;
//rest of method
return StatusCode(201);
}
It works fine, although in the SwaggerUI
page that gets created there's no mention of the method expecting a file in the body.它工作正常,尽管在创建的SwaggerUI
页面中没有提到需要正文中的文件的方法。 Is there a way to specify the method expects a file in the generated SwaggerUI
page?有没有办法指定方法需要生成的SwaggerUI
页面中的文件?
I can simulate the input using the following piece of code:我可以使用以下代码模拟输入:
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
}
The file upload is not documented because it's not a param in the action method.文件上传没有记录,因为它不是 action 方法中的参数。 Swagger has no way of knowing what you're doing inside the action itself. Swagger 无法知道您在动作本身内部在做什么。 Attempting to handle a file upload this way is bad practice anyways.无论如何,尝试以这种方式处理文件上传是不好的做法。 You can use IFormFile
, but that only works if your request body is encoded as multipart/form-data
.您可以使用IFormFile
,但只有当您的请求正文被编码为multipart/form-data
时才有效。 If you're dealing with JSON or basically anything that qualifies as FromBody
, then you need to bind to a byte[]
:如果您正在处理 JSON 或基本上任何符合FromBody
条件的FromBody
,那么您需要绑定到byte[]
:
[HttpPut("Test/{id}")]
public IActionResult PutTest(string id, byte[] file)
{
//rest of method
return StatusCode(201);
}
Now, the automatic FromBody
applied by the [ApiController]
attribute only works with class types, so I'm not sure off the top of my head whether it will apply to a byte[]
.现在, [ApiController]
属性应用的自动FromBody
仅适用于类类型,所以我不确定它是否适用于byte[]
。 If not, just do:如果没有,只需执行以下操作:
public IActionResult PutTest(string id, [FromBody]byte[] file)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.