是否可以使用Swashbuckle为其中一个属性生成引用的架构



默认情况下,Swashbuckle其中一个属性(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生成器等工具目前仅支持上述格式。因此,任何为其中一个属性生成引用模式的变通方法都是值得赞赏的。

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

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; }
}

然后,我们需要将该属性用于属于类型的模型的属性。在下面的片段中,我使用了前缀";OneOfProp";,因此生成的新模式将具有此前缀

public class ModelClass
{

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

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

最后在服务中注册此过滤器

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

最新更新