[英]How to swagger-document an ASP.NET Core action which reads Request.Body directly
我有一个 Controller 操作方法,它直接(而不是使用文件)读取Request.Body
用于流式传输和其他目的。 问题是没有 model 绑定,因此 Swagger 没有记录合同。 例如:
[HttpPost("upload")]
[DisableFormValueModelBinding]
public async Task<IActionResult> UploadAsync()
{
// Read from Request.Body manually, expecting content type to be multipart/*
return Ok();
}
加载Swagger UI时,无法上传文件等。
有没有办法通过 ASP.NET 核心中的属性来支持这一点?
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); ;
}
操作过滤器
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"
}
};
}
}
}
启动-ConfigureServices
services.AddSwaggerGen(
options =>
{
options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { Title = "My API", Version = "v1" });
options.OperationFilter<SwaggerFileOperationFilter>();
});
来源是: 在此处输入链接描述
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.