是否可以使用 Swashbuckle 为其中一个属性生成引用模式?

Is it possible to generate referenced schema for oneof properties using Swashbuckle?

默认情况下,Swashbuckleoneof 属性(universeCategory)生成一个内联模式,如下所示。

"Universe":{
  "type":"object",
  "properties":{
    "universeCategory":{
      "oneOf":[
        {
          "$ref":"#/components/schemas/FullUniverse"
        },
        {
          "$ref":"#/components/schemas/HalfUniverse"
        }
      ],
      "discriminator":{
        "propertyName":"source",
        "mapping":{
          "FullUniverse":"#/components/schemas/FullUniverse",
          "HalfUniverse":"#/components/schemas/HalfUniverse"
        }
      }
    }
  }
}

是否可以通过将一些配置传递给 Swashbuckle 来生成如下所示的引用模式?

"Universe":{
  "type":"object",
  "properties":{
    "universe":{
      "$ref":"#/components/schemas/UniverseCategory"
    }
  },
  "additionalProperties":false
},
"UniverseCategory":{
  "oneOf":[
    {
      "$ref":"#/components/schemas/HalfUniverse"
    },
    {
      "$ref":"#/components/schemas/FullUniverse"
    }
  ],
  "discriminator":{
    "propertyName":"source",
    "mapping":{
      "HalfUniverse":"#/components/schemas/HalfUniverse",
      "FullUniverse":"#/components/schemas/FullUniverse"
    }
  }
}

Open API generator 等工具目前仅支持上述格式。因此,欢迎任何为 oneof 属性生成引用模式的解决方法。

我们可以添加一个自定义过滤器来处理其中一个模式作为单独模式的生成,并可以添加对生成的新模式的引用。

public class HandleOneOfPropertiesFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        if (schema?.Properties == null || context.Type == null)
        {
            return;
        }
        
        var propertiesWithOneOfHandling = context.Type.GetProperties()
            .Where(t => t.GetCustomAttributes().Any(c => c.GetType() == typeof(HandleOneOfPropertiesAttribute)));

        foreach (var selectedProps in propertiesWithOneOfHandling)
        {

            foreach (var props in schema.Properties)
            {
                if (selectedProps.Name.Equals(props.Key, StringComparison.InvariantCultureIgnoreCase))
                {
                    var oneOfProperty = (HandleOneOfPropertiesAttribute)context.Type.GetProperty(selectedProps.Name)
                        .GetCustomAttribute(typeof(HandleOneOfPropertiesAttribute));
                    
                    var name = oneOfProperty.Prefix + selectedProps.Name;

                    if (props.Value.Type == "array")
                    {
                        // Handling array type differently
                        context.SchemaRepository.Schemas.Add(name, props.Value.Items);
                        
                        var newSchema = new OpenApiSchema();
                        newSchema.Type = "array";
                        newSchema.Items  = new OpenApiSchema
                        {
                            Reference = new OpenApiReference
                            {
                                Id = name,
                                Type = ReferenceType.Schema
                            }
                        };
                        context.SchemaRepository.Schemas.Add(name + "Array", newSchema);
                        props.Value.Reference = new OpenApiReference
                        {
                            Id = name + "Array",
                            Type = ReferenceType.Schema
                        };
                    }
                    else
                    {
                        context.SchemaRepository.Schemas.Add(name, props.Value);    
                        props.Value.Reference = new OpenApiReference
                        {
                            Id = name,
                            Type = ReferenceType.Schema
                        };
                    }
                }
            }
        }
    }
}

然后我们需要定义一个属性来标识我们需要处理生成的属性,让我们创建属性

public class HandleOneOfPropertiesAttribute : Attribute
{
    public HandleOneOfPropertiesAttribute(string prefix)
    {
        Prefix = prefix;
    }
    
    public string Prefix { get; }
}

然后我们需要将这个属性用于oneof类型的模型属性。 在下面的代码片段中,我使用了前缀“OneOfProp”,因此生成的新模式将具有此前缀

public class ModelClass
{
   
    [HandleOneOfProperties("OneOfProp")]
    public Universe property1 { get; set; }


    [HandleOneOfProperties("OneOfProp")]
    public Galaxy property2 { get; set; }
}

最后在服务中注册这个过滤器

services.AddSwaggerGen(c =>
 {
   c.SchemaFilter<HandleOneOfPropertiesFilter>();
 });