You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 19:47:01