如何解决如何大摇大摆地记录直接读取 Request.Body 的 ASP.NET Core 操作
我有一个控制器操作方法,它直接读取 Request.Body
(而不是使用 File)用于流式传输和其他目的。问题是没有模型绑定,因此 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 Core 中的属性支持这一点?
解决方法
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"
}
};
}
}
}
启动-配置服务
services.AddSwaggerGen(
options =>
{
options.SwaggerDoc("v1",new Swashbuckle.AspNetCore.Swagger.Info { Title = "My API",Version = "v1" });
options.OperationFilter<SwaggerFileOperationFilter>();
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。