.net core webapi 文件上传在 Swagger 文档中的有好提示处理
前提:
需要nuget Swashbuckle.AspNetCore 我暂时用的是 4.01 最新版本;
描述:解决 .net core webapi 上传文件使用的是 IFormFile,在Swagger 接口描叙的时候很不友好,为解决接口文档的友好描叙;
实际效果:
解决办法:
步骤1 增加 Swagger 的选项过滤器 SwaggerFileUploadFilter.cs
/// <summary> /// Swagger 上传文件过滤器 /// </summary> public class SwaggerFileUploadFilter : IOperationFilter { /// <summary> /// 应用过滤器 /// </summary> /// <param name="operation"></param> /// <param name="context"></param> public void Apply(Operation operation, OperationFilterContext context) { #region 文件上传处理 if (!context.ApiDescription.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase) && !context.ApiDescription.HttpMethod.Equals("PUT", StringComparison.OrdinalIgnoreCase)) { return; } var fileParameters = context.ApiDescription.ActionDescriptor.Parameters.Where(n => n.ParameterType == typeof(IFormFile)).ToList(); if (fileParameters.Count < 0) { return; } operation.Consumes.Add("multipart/form-data"); foreach (var fileParameter in fileParameters) { var parameter = operation.Parameters.Single(n => n.Name == fileParameter.Name); operation.Parameters.Remove(parameter); operation.Parameters.Add(new NonBodyParameter { Name = parameter.Name, In = "formData", Description = parameter.Description, Required = parameter.Required, Type = "file" }); } #endregion } }
步骤2 对 startup.cs swagger 配置项进行过滤
services.AddSwaggerGen(options => { .......... options.OperationFilter<SwaggerFileUploadFilter>(); });