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

如何让Swashbuckle为Dictionary参数生成正确的OpenAPI schema?

解决Swashbuckle为Dictionary查询参数生成正确OpenAPI Schema的问题

我之前也碰到过这个情况,Swashbuckle默认对Dictionary<string, string>类型的查询参数生成的Schema没法满足你要的values[someProperty]=123这种请求格式需求,不过通过自定义一个参数过滤器就能搞定,具体步骤如下:

1. 创建自定义参数过滤器

这个过滤器会识别出Dictionary<string, string>类型的参数,然后调整它的OpenAPI Schema配置,指定为object类型并启用deepObject风格的参数解析:

using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Collections.Generic;

public class DictionaryQueryParameterFilter : IParameterFilter
{
    public void Apply(OpenApiParameter parameter, ParameterFilterContext context)
    {
        var paramType = context.ParameterInfo.ParameterType;
        
        // 检查是否是我们要处理的Dictionary<string, string>类型
        if (paramType.IsGenericType 
            && paramType.GetGenericTypeDefinition() == typeof(Dictionary<,>)
            && paramType.GetGenericArguments()[0] == typeof(string)
            && paramType.GetGenericArguments()[1] == typeof(string))
        {
            // 设置Schema为object,允许任意string键值对
            parameter.Schema = new OpenApiSchema
            {
                Type = "object",
                AdditionalProperties = new OpenApiSchema { Type = "string" }
            };
            
            // 设置参数风格为DeepObject,这样Swagger会生成values[xxx]的格式
            parameter.Style = ParameterStyle.DeepObject;
            parameter.Explode = true;
        }
    }
}

2. 注册过滤器到Swagger配置

根据你的.NET版本,在Swagger的服务配置中添加这个过滤器:

.NET 6+(Program.cs)

builder.Services.AddSwaggerGen(c =>
{
    // 注册自定义参数过滤器
    c.ParameterFilter<DictionaryQueryParameterFilter>();
    
    // 其他Swagger配置(比如文档信息、XML注释等)
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "Test API", Version = "v1" });
});

.NET 5及更早版本(Startup.cs)

public void ConfigureServices(IServiceCollection services)
{
    services.AddSwaggerGen(c =>
    {
        c.ParameterFilter<DictionaryQueryParameterFilter>();
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "Test API", Version = "v1" });
    });
}

3. 验证效果

启动你的API项目后,打开Swagger UI,你会看到values参数被展示为一个可扩展的对象,输入键值对后生成的请求URL会自动变成http://localhost:36541/api?values[someProperty]=123&values[someOther]=234的格式,对应的swagger.json里的Schema也会正确描述这个Dictionary参数的结构。

内容的提问来源于stack exchange,提问作者Magnus Johansson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:38:36