.NET 8 Minimal API中NSwag无法正确生成模型内IFormFile的Swagger文档
解决.NET 8 Minimal API中NSwag无法正确识别模型内IFormFile的问题
问题原因
NSwag旧版本对.NET 8 Minimal API中嵌套在模型类里的IFormFile类型支持不完善,未能自动将其识别为文件上传参数,导致Swagger UI显示为普通字符串输入框。
解决方案
1. 升级NSwag.AspNetCore版本
首先将项目中的NSwag.AspNetCore包升级到14.1.8及以上版本(该版本修复了.NET 8 Minimal API的若干兼容问题)。修改项目文件中的包引用:
<PackageReference Include="NSwag.AspNetCore" Version="14.1.8" />
2. 添加自定义Schema处理器
通过自定义ISchemaProcessor,强制NSwag将IFormFile类型标记为Swagger可识别的文件类型,并确保包含该类型的模型对应的请求使用multipart/form-data格式。
步骤1:定义Schema处理器类
using NSwag.Generation.Processors; using NSwag.Generation.Processors.Contexts; using Microsoft.AspNetCore.Http; using System.Reflection; public class FileUploadSchemaProcessor : ISchemaProcessor { public void Process(SchemaProcessorContext context) { // 直接处理IFormFile类型 if (context.Type == typeof(IFormFile)) { context.Schema.Type = "string"; context.Schema.Format = "binary"; return; } // 处理包含IFormFile属性的模型类 if (!context.Type.IsClass || context.Type == typeof(string)) return; foreach (PropertyInfo property in context.Type.GetProperties()) { if (property.PropertyType == typeof(IFormFile)) { // 标记模型对应的请求需使用multipart/form-data context.Schema.Extensions["x-content-type"] = "multipart/form-data"; break; } } } }
步骤2:注册Schema处理器
在配置OpenAPI文档时添加该处理器:
builder.Services.AddOpenApiDocument(config => { config.DocumentName = "Test"; config.Title = "Test v1"; config.Version = "v1"; // 注册自定义Schema处理器 config.SchemaProcessors.Add(new FileUploadSchemaProcessor()); });
3. 可选:添加Operation处理器增强兼容性
如果上述步骤后仍存在问题,可添加IOperationProcessor确保请求的编码设置正确:
using NSwag.Generation.Processors; using NSwag.Generation.Processors.Contexts; builder.Services.AddOpenApiDocument(config => { // ... 其他配置 ... config.OperationProcessors.Add(new OperationProcessor(context => { if (context.OperationDescription.Operation.RequestBody?.Content.TryGetValue("multipart/form-data", out var content) ?? false) { foreach (var prop in content.Schema.Properties) { if (prop.Value.Type == "string" && prop.Value.Format == "binary") { content.Encoding[prop.Key] = new NSwag.OpenApiEncoding { ContentType = "application/octet-stream" }; } } } return true; })); });
验证
启动项目后访问Swagger UI(默认路径/swagger),查看/upload端点的参数:File字段应显示为文件上传选择框,请求类型自动设为multipart/form-data。
内容的提问来源于stack exchange,提问作者awattar
相关产品推荐
相关产品推荐

