如何在Swagger中显示IFormFile参数的描述信息
问题:IFormFile参数无法在Swagger中显示描述信息
我在使用IFormFile作为上传接口参数时,无法为其添加Swagger描述信息。接口代码如下:
[Route("service")] public class WebServiceController : Controller { /// <summary> /// 文件上传接口 /// </summary> /// <param name="file">待上传的文件</param> /// <response code="200">文件上传成功</response> [HttpPost("upload")] public IActionResult Upload(IFormFile file) { ... } }
我已经在Startup.cs中配置了Swagger的XML注释支持:
... services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = $"WebService API V1 ({GetType().Assembly.GetName().Version})", Version = "v1" }); // 设置Swagger JSON和UI的注释文件路径 var xmlFile = $"{typeof(Startup).Assembly.GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); });
(附图:描述缺失)
但无论Swagger UI还是swagger.json中,都看不到该参数的描述信息,请问如何让描述生效?
解决方法:扩展OperationFilter支持DescriptionAttribute
感谢bugrakosen的解答,我在此基础上扩展了过滤器,使其支持DescriptionAttribute来为IFormFile参数添加描述。
1. 为接口参数添加DescriptionAttribute
修改接口方法,给IFormFile参数加上[Description]特性:
... [HttpPost("upload")] public IActionResult Upload([Description("待上传的目标文件")] IFormFile file) { ... }
2. 实现自定义OperationFilter
创建SwaggerFileOperationFilter类,实现IOperationFilter接口:
internal class SwaggerFileOperationFilter : IOperationFilter { public void Apply(OpenApiOperation operation, OperationFilterContext context) { var fileUploadMime = "multipart/form-data"; if (operation.RequestBody == null || !operation.RequestBody.Content.Any(x => x.Key.Equals(fileUploadMime, StringComparison.InvariantCultureIgnoreCase))) { return; } var methodParameters = context.MethodInfo.GetParameters(); foreach (var schemaProperty in operation.RequestBody.Content[fileUploadMime].Schema.Properties) { var descriptionAttr = methodParameters.FirstOrDefault(param => param.Name == schemaProperty.Key)? .GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault() as DescriptionAttribute; if (descriptionAttr != null) { schemaProperty.Value.Description = descriptionAttr.Description; } } } }
3. 将过滤器注册到Swagger
在Startup.cs的AddSwaggerGen配置中添加该过滤器:
services.AddSwaggerGen(c => { // 原有配置... c.OperationFilter<SwaggerFileOperationFilter>(); });
完成以上配置后,Swagger UI和swagger.json中就能正确显示IFormFile参数的描述信息了。
内容的提问来源于stack exchange,提问作者Rod
相关产品推荐
相关产品推荐

