我在c#中有一个Asp.Net web API 5.2项目,并使用Swashbuckle生成文档。
我的模型包含继承,比如从Animal抽象类中获取Animal属性,从中派生出Dog和Cat类。
Swashbuckle只显示Animal类的架构,所以我尝试使用ISchemaFilter(他们也建议使用它),但我无法使其工作,而且我找不到合适的例子。
有人可以帮忙吗?
答案 0 :(得分:23)
似乎Swashbuckle没有正确实现多态,我理解作者关于子类作为参数的观点(如果一个动作需要一个Animal类,如果你用一个狗对象或一只猫来调用它,行为会有所不同对象,然后你应该有2个不同的动作...)但作为返回类型我相信返回Animal是正确的,对象可能是Dog或Cat类型。
所以要描述我的API并根据正确的指导方针生成一个合适的JSON模式(请注意我描述的判断器的方式,如果你有自己的鉴别器,你可能需要特别改变那个部分),我使用文档和架构过滤器如下:
{
"definitions": {
"Pet": {
"type": "object",
"discriminator": "petType",
"properties": {
"name": {
"type": "string"
},
"petType": {
"type": "string"
}
},
"required": [
"name",
"petType"
]
},
"Cat": {
"description": "A representation of a cat",
"allOf": [
{
"$ref": "#/definitions/Pet"
},
{
"type": "object",
"properties": {
"huntingSkill": {
"type": "string",
"description": "The measured skill for hunting",
"default": "lazy",
"enum": [
"clueless",
"lazy",
"adventurous",
"aggressive"
]
}
},
"required": [
"huntingSkill"
]
}
]
},
"Dog": {
"description": "A representation of a dog",
"allOf": [
{
"$ref": "#/definitions/Pet"
},
{
"type": "object",
"properties": {
"packSize": {
"type": "integer",
"format": "int32",
"description": "the size of the pack the dog is from",
"default": 0,
"minimum": 0
}
},
"required": [
"packSize"
]
}
]
}
}
}
前面的代码实现的内容在{"具有多态性支持的模型'部分中指定了here。它基本上产生如下内容:
python setup.py install
答案 1 :(得分:10)
要继续保罗的最佳答案,如果您使用的是Swagger 2.0,则需要修改如下所示的类:
public class PolymorphismSchemaFilter<T> : ISchemaFilter
{
private readonly Lazy<HashSet<Type>> derivedTypes = new Lazy<HashSet<Type>>(Init);
private static HashSet<Type> Init()
{
var abstractType = typeof(T);
var dTypes = abstractType.Assembly
.GetTypes()
.Where(x => abstractType != x && abstractType.IsAssignableFrom(x));
var result = new HashSet<Type>();
foreach (var item in dTypes)
result.Add(item);
return result;
}
public void Apply(Schema model, SchemaFilterContext context)
{
if (!derivedTypes.Value.Contains(context.SystemType)) return;
var clonedSchema = new Schema
{
Properties = model.Properties,
Type = model.Type,
Required = model.Required
};
//schemaRegistry.Definitions[typeof(T).Name]; does not work correctly in SwashBuckle
var parentSchema = new Schema { Ref = "#/definitions/" + typeof(T).Name };
model.AllOf = new List<Schema> { parentSchema, clonedSchema };
//reset properties for they are included in allOf, should be null but code does not handle it
model.Properties = new Dictionary<string, Schema>();
}
}
public class PolymorphismDocumentFilter<T> : IDocumentFilter
{
private static void RegisterSubClasses(ISchemaRegistry schemaRegistry, Type abstractType)
{
const string discriminatorName = "discriminator";
var parentSchema = schemaRegistry.Definitions[abstractType.Name];
//set up a discriminator property (it must be required)
parentSchema.Discriminator = discriminatorName;
parentSchema.Required = new List<string> { discriminatorName };
if (!parentSchema.Properties.ContainsKey(discriminatorName))
parentSchema.Properties.Add(discriminatorName, new Schema { Type = "string" });
//register all subclasses
var derivedTypes = abstractType.Assembly
.GetTypes()
.Where(x => abstractType != x && abstractType.IsAssignableFrom(x));
foreach (var item in derivedTypes)
schemaRegistry.GetOrRegister(item);
}
public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
{
RegisterSubClasses(context.SchemaRegistry, typeof(T));
}
}
答案 2 :(得分:8)
我们最近升级到了.NET Core 3.1和Swashbuckle.AspNetCore 5.0 而且API有所更改。 如果有人需要此过滤器,则这里的代码经过最少的更改即可获得类似的行为:
public class PolymorphismDocumentFilter<T> : IDocumentFilter
{
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
RegisterSubClasses(context.SchemaRepository, context.SchemaGenerator, typeof(T));
}
private static void RegisterSubClasses(SchemaRepository schemaRegistry, ISchemaGenerator schemaGenerator, Type abstractType)
{
const string discriminatorName = "$type";
OpenApiSchema parentSchema = null;
if (schemaRegistry.TryGetIdFor(abstractType, out string parentSchemaId))
parentSchema = schemaRegistry.Schemas[parentSchemaId];
else
parentSchema = schemaRegistry.GetOrAdd(abstractType, parentSchemaId, () => new OpenApiSchema());
// set up a discriminator property (it must be required)
parentSchema.Discriminator = new OpenApiDiscriminator() { PropertyName = discriminatorName };
parentSchema.Required = new HashSet<string> { discriminatorName };
if (parentSchema.Properties == null)
parentSchema.Properties = new Dictionary<string, OpenApiSchema>();
if (!parentSchema.Properties.ContainsKey(discriminatorName))
parentSchema.Properties.Add(discriminatorName, new OpenApiSchema() { Type = "string", Default = new OpenApiString(abstractType.FullName) });
// register all subclasses
var derivedTypes = abstractType.GetTypeInfo().Assembly.GetTypes()
.Where(x => abstractType != x && abstractType.IsAssignableFrom(x));
foreach (var item in derivedTypes)
schemaGenerator.GenerateSchema(item, schemaRegistry);
}
}
public class PolymorphismSchemaFilter<T> : ISchemaFilter
{
private readonly Lazy<HashSet<Type>> derivedTypes = new Lazy<HashSet<Type>>(Init);
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
if (!derivedTypes.Value.Contains(context.Type)) return;
Type type = context.Type;
var clonedSchema = new OpenApiSchema
{
Properties = schema.Properties,
Type = schema.Type,
Required = schema.Required
};
// schemaRegistry.Definitions[typeof(T).Name]; does not work correctly in Swashbuckle.AspNetCore
var parentSchema = new OpenApiSchema
{
Reference = new OpenApiReference() { ExternalResource = "#/definitions/" + typeof(T).Name }
};
var assemblyName = Assembly.GetAssembly(type).GetName();
schema.Discriminator = new OpenApiDiscriminator() { PropertyName = "$type" };
// This is required if you use Microsoft's AutoRest client to generate the JavaScript/TypeScript models
schema.Extensions.Add("x-ms-discriminator-value", new OpenApiObject() { ["name"] = new OpenApiString($"{type.FullName}, {assemblyName.Name}") });
schema.AllOf = new List<OpenApiSchema> { parentSchema, clonedSchema };
// reset properties for they are included in allOf, should be null but code does not handle it
schema.Properties = new Dictionary<string, OpenApiSchema>();
}
private static HashSet<Type> Init()
{
var abstractType = typeof(T);
var dTypes = abstractType.GetTypeInfo().Assembly
.GetTypes()
.Where(x => abstractType != x && abstractType.IsAssignableFrom(x));
var result = new HashSet<Type>();
foreach (var item in dTypes)
result.Add(item);
return result;
}
}
我没有完全检查结果,但是看来它具有相同的行为。
还请注意,您需要导入以下名称空间:
using Microsoft.OpenApi.Models;
using Microsoft.OpenApi.Any;
using System.Reflection;
using Swashbuckle.AspNetCore.SwaggerGen;
答案 3 :(得分:7)
从this merge开始到Swashbuckle.AspNetCore,您可以使用以下方法获得对多态模式的基本支持:
services.AddSwaggerGen(c =>
{
c.GeneratePolymorphicSchemas();
}
您还可以通过注释库中存在的属性来表示派生类型:
[SwaggerSubTypes(typeof(SubClass), Discriminator = "value")]
This article详细介绍了如何使用Newtonsoft反序列化派生类型。
答案 4 :(得分:3)
我想跟进克雷格的回答。
如果您使用NSwag使用Paulo's answer中说明的方法从Swashbuckle(在撰写本文时为3.x)生成的Swagger API文档中生成TypeScript定义,则将在Craig's answer中进行增强可能会遇到以下问题:
生成的TypeScript定义将具有重复的属性,即使生成的类将扩展基类也是如此。考虑以下C#类:
public abstract class BaseClass
{
public string BaseProperty { get; set; }
}
public class ChildClass : BaseClass
{
public string ChildProperty { get; set; }
}
使用上述答案时,IBaseClass
和IChildClass
接口的结果TypeScript定义如下所示:
export interface IBaseClass {
baseProperty : string | undefined;
}
export interface IChildClass extends IBaseClass {
baseProperty : string | undefined;
childProperty: string | undefined;
}
如您所见,baseProperty
在基类和子类中均未正确定义。为了解决这个问题,我们可以修改Apply
类的PolymorphismSchemaFilter<T>
方法,以仅将拥有的属性包括到架构中,即从当前类型的架构中排除继承的属性。这是一个示例:
public void Apply(Schema model, SchemaFilterContext context)
{
...
// Prepare a dictionary of inherited properties
var inheritedProperties = context.SystemType.GetProperties()
.Where(x => x.DeclaringType != context.SystemType)
.ToDictionary(x => x.Name, StringComparer.OrdinalIgnoreCase);
var clonedSchema = new Schema
{
// Exclude inherited properties. If not excluded,
// they would have appeared twice in nswag-generated typescript definition
Properties =
model.Properties.Where(x => !inheritedProperties.ContainsKey(x.Key))
.ToDictionary(x => x.Key, x => x.Value),
Type = model.Type,
Required = model.Required
};
...
}
生成的TypeScript定义将不引用任何现有的中间抽象类的属性。考虑以下C#类:
public abstract class SuperClass
{
public string SuperProperty { get; set; }
}
public abstract class IntermediateClass : SuperClass
{
public string IntermediateProperty { get; set; }
}
public class ChildClass : BaseClass
{
public string ChildProperty { get; set; }
}
在这种情况下,生成的TypeScript定义将如下所示:
export interface ISuperClass {
superProperty: string | undefined;
}
export interface IIntermediateClass extends ISuperClass {
intermediateProperty : string | undefined;
}
export interface IChildClass extends ISuperClass {
childProperty: string | undefined;
}
请注意,生成的IChildClass
接口如何直接扩展ISuperClass
,而忽略了IIntermediateClass
接口,实际上使IChildClass
的任何实例都没有intermediateProperty
属性。< / p>
我们可以使用以下代码解决此问题:
public void Apply(Schema model, SchemaFilterContext context)
{
...
// Use the BaseType name for parentSchema instead of typeof(T),
// because we could have more classes in the hierarchy
var parentSchema = new Schema
{
Ref = "#/definitions/" + (context.SystemType.BaseType?.Name ?? typeof(T).Name)
};
...
}
这将确保子类正确引用中间类。
最后,最终代码将如下所示:
public void Apply(Schema model, SchemaFilterContext context)
{
if (!derivedTypes.Value.Contains(context.SystemType))
{
return;
}
// Prepare a dictionary of inherited properties
var inheritedProperties = context.SystemType.GetProperties()
.Where(x => x.DeclaringType != context.SystemType)
.ToDictionary(x => x.Name, StringComparer.OrdinalIgnoreCase);
var clonedSchema = new Schema
{
// Exclude inherited properties. If not excluded,
// they would have appeared twice in nswag-generated typescript definition
Properties =
model.Properties.Where(x => !inheritedProperties.ContainsKey(x.Key))
.ToDictionary(x => x.Key, x => x.Value),
Type = model.Type,
Required = model.Required
};
// Use the BaseType name for parentSchema instead of typeof(T),
// because we could have more abstract classes in the hierarchy
var parentSchema = new Schema
{
Ref = "#/definitions/" + (context.SystemType.BaseType?.Name ?? typeof(T).Name)
};
model.AllOf = new List<Schema> { parentSchema, clonedSchema };
// reset properties for they are included in allOf, should be null but code does not handle it
model.Properties = new Dictionary<string, Schema>();
}
答案 5 :(得分:3)
这适用于 5.6.3 版:
services.AddSwaggerGen(options =>
{
options.UseOneOfForPolymorphism();
options.SelectDiscriminatorNameUsing(_ => "type");
});