[英]How to swagger-document an ASP.NET Core action which reads Request.Body directly
I have a Controller action method which reads the Request.Body
directly (instead of using File) for streaming and other purposes.我有一个 Controller 操作方法,它直接(而不是使用文件)读取Request.Body
用于流式传输和其他目的。 The problem is there is no model binding and therefore Swagger doesn't document the contract.问题是没有 model 绑定,因此 Swagger 没有记录合同。 For example:例如:
[HttpPost("upload")]
[DisableFormValueModelBinding]
public async Task<IActionResult> UploadAsync()
{
// Read from Request.Body manually, expecting content type to be multipart/*
return Ok();
}
When loading Swagger UI, there is no way to upload a file, etc.加载Swagger UI时,无法上传文件等。
Is there any way to support this with attributes in ASP.NET Core?有没有办法通过 ASP.NET 核心中的属性来支持这一点?
The API: API:
[HttpPost]
public async Task<IActionResult> Post(
[FromForm(Name = "myFile")]IFormFile myFile)
{
using (var fileContentStream = new MemoryStream())
{
await myFile.CopyToAsync(fileContentStream);
await System.IO.File.WriteAllBytesAsync(Path.Combine(folderPath, myFile.FileName), fileContentStream.ToArray());
}
return CreatedAtRoute(routeName: "myFile", routeValues: new { filename = myFile.FileName }, value: null); ;
}
Operation filter操作过滤器
public class SwaggerFileOperationFilter : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
if (operation.OperationId == "Post")
{
operation.Parameters = new List<IParameter>
{
new NonBodyParameter
{
Name = "myFile",
Required = true,
Type = "file",
In = "formData"
}
};
}
}
}
Startup- ConfigureServices启动-ConfigureServices
services.AddSwaggerGen(
options =>
{
options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { Title = "My API", Version = "v1" });
options.OperationFilter<SwaggerFileOperationFilter>();
});
The result in swagger UI: swagger UI 中的结果:
The source is: enter link description here来源是: 在此处输入链接描述
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.