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

在Swashbuckle文档过滤器中获取自定义属性实现Schema属性排序

解决方案

你之前的实现方向存在两个核心问题:

  • 选用了IDocumentFilter而非专用于Schema结构处理的ISchemaFilter,前者只能拿到最终生成的OpenApi结构,无法关联原始CLR类型的元数据
  • 尝试从接口方法的MethodInfo读取DTO属性的自定义特性,元数据来源完全不匹配

步骤1:实现ISchemaFilter接口

直接用ISchemaFilter可以在Schema生成阶段拿到对应CLR类型的完整元数据,直接读取属性上的SwaggerOrderAttribute即可:

public class SchemaOrderFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        // 只处理有属性的Schema
        if (schema.Properties == null || !schema.Properties.Any())
            return;

        // 读取当前类型所有属性的SwaggerOrderAttribute配置,按属性名做映射
        var propertyOrderMap = context.Type.GetProperties()
            .ToDictionary(
                prop => prop.Name,
                prop => prop.GetCustomAttribute<SwaggerOrderAttribute>()?.Order ?? int.MaxValue
                // 没有加排序特性的属性默认排在最后,也可以改成0排在最前,按需调整
            );

        // 重新排序属性:先按Order升序,再按属性名升序
        var sortedProperties = schema.Properties
            .OrderBy(p => propertyOrderMap.TryGetValue(p.Key, out var order) ? order : int.MaxValue)
            .ThenBy(p => p.Key)
            .ToList();

        // 清空原有属性,按排序后的顺序重新添加
        schema.Properties.Clear();
        foreach (var prop in sortedProperties)
        {
            schema.Properties.Add(prop.Key, prop.Value);
        }
    }
}

步骤2:注册过滤器

在Swagger配置处注册上述过滤器,示例(.NET 5 Startup.cs的ConfigureServices方法):

services.AddSwaggerGen(options =>
{
    // 你原有其他Swagger配置
    options.SchemaFilter<SchemaOrderFilter>();
});

可选:针对特定模型生效

如果你不需要全局生效,只想给指定模型启用排序,只需要在Apply方法最开始加类型判断即可:

// 仅处理SupporterDTO
if (context.Type != typeof(SupporterDTO))
    return;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 01:51:00