.NET Core Minimal API文件上传Swagger未显示参数名求解决办法
可行的替代解决方案
方案1:手动在OpenAPI配置中补充参数名称
直接在WithOpenApi方法里手动添加表单参数的名称,让Swagger页面能正确渲染出参数输入项:
app.MapPost("/ReadPDF", async (IFormFile file) => { string tempfile = CreateTempfilePath(); using var stream = File.OpenWrite(tempfile); await file.CopyToAsync(stream); StringBuilder sbPDFText = new StringBuilder(); // 省略PDF文本解析逻辑... return sbPDFText.ToString(); }) .WithName("ReadPDF") .WithOpenApi(operation => { var modifiedOperation = new OpenApiOperation(operation); modifiedOperation.Summary = "Reads text from PDF"; modifiedOperation.Description = "This API returns all text in PDF document"; // 手动指定表单参数名和类型 if (modifiedOperation.RequestBody?.Content.TryGetValue("multipart/form-data", out var content) == true) { content.Schema.Properties = new Dictionary<string, OpenApiSchema> { ["file"] = new OpenApiSchema { Type = "string", Format = "binary", Description = "待上传的PDF文件" } }; } return modifiedOperation; });
方案2:用DTO类包装IFormFile参数
将IFormFile封装到一个DTO类中,Swashbuckle会自动识别参数名并在Swagger页面正确展示:
// 定义上传请求DTO public class PdfUploadRequest { public IFormFile File { get; set; } = null!; } // 修改API端点逻辑 app.MapPost("/ReadPDF", async (PdfUploadRequest request) => { string tempfile = CreateTempfilePath(); using var stream = File.OpenWrite(tempfile); await request.File.CopyToAsync(stream); StringBuilder sbPDFText = new StringBuilder(); // 省略PDF文本解析逻辑... return sbPDFText.ToString(); }) .WithName("ReadPDF") .WithOpenApi(operation => new(operation) { Summary = "Reads text from PDF", Description = "This API returns all text in PDF document" });
方案3:自定义Swagger过滤器自动补全参数名
创建一个全局过滤器,自动为所有IFormFile类型的参数补充正确的表单名称,无需修改原有API代码:
// 自定义操作过滤器 public class FormFileParameterFilter : IOperationFilter { public void Apply(OpenApiOperation operation, OperationFilterContext context) { var formFileParams = context.MethodInfo.GetParameters() .Where(p => p.ParameterType == typeof(IFormFile)); if (!formFileParams.Any()) return; // 确保multipart/form-data类型的请求体存在 if (operation.RequestBody?.Content.TryGetValue("multipart/form-data", out var content) != true) { content = new OpenApiMediaType { Schema = new OpenApiSchema { Type = "object", Properties = new Dictionary<string, OpenApiSchema>() } }; operation.RequestBody = new OpenApiRequestBody { Content = { ["multipart/form-data"] = content } }; } // 为每个IFormFile参数添加对应的表单项 foreach (var param in formFileParams) { content.Schema.Properties[param.Name] = new OpenApiSchema { Type = "string", Format = "binary", Description = param.Name }; } } } // 在Swagger服务注册时添加过滤器 builder.Services.AddSwaggerGen(c => { c.OperationFilter<FormFileParameterFilter>(); });
内容的提问来源于stack exchange,提问作者Adil
相关产品推荐
相关产品推荐

