using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using Microsoft.AspNetCore.Http; using System.Reflection; using System.Linq; namespace FutureMailAPI.Helpers { /// /// Swagger文件上传操作过滤器 /// public class FileUploadOperationFilter : 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 fileParams = context.MethodInfo.GetParameters() .Where(p => p.ParameterType == typeof(IFormFile) || (p.ParameterType.IsClass && p.ParameterType.GetProperties().Any(prop => prop.PropertyType == typeof(IFormFile)))) .ToList(); if (!fileParams.Any()) return; operation.RequestBody.Content[fileUploadMime].Schema.Properties = fileParams.ToDictionary(k => k.Name!, v => new OpenApiSchema() { Type = "string", Format = "binary" }); } } }