使用Swashbuckle for Asp.net核心如何将模型添加到生成的模型列表中?

chr*_*389 7 swagger-2.0 swashbuckle asp.net-core

我正在使用Swashbuckle和ASP.net核心.它正在制作一个很棒的网站,底部有一个模型列表.

在此输入图像描述

如何将此模型添加到尚未显示​​的列表中?

我在其中一个请求中返回一个抽象类,我想列出继承该抽象类的所有变体.

提前致谢

Tse*_*eng 10

您可以创建文档过滤器并在全局注册.

public class CustomModelDocumentFilter<T> : IDocumentFilter where T : class
{
    public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
    {
        context.SchemaRegistry.GetOrRegister(typeof(T));
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在你的Startup课堂上注册.

services.AddSwaggerGen(options =>
{
    ...
    options.DocumentFilter<CustomModelDocumentFilter<MyCustomModel>>();
    options.DocumentFilter<CustomModelDocumentFilter<MyOtherModel>>();
    ...
}
Run Code Online (Sandbox Code Playgroud)

对于多态类,您可以使用这些来过滤(这个答案略有改进的版本).

public class PolymorphismDocumentFilter<T> : IDocumentFilter
{
    public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
    {
        RegisterSubClasses(context.SchemaRegistry, typeof(T));
    }

    private static void RegisterSubClasses(ISchemaRegistry schemaRegistry, Type abstractType)
    {
        const string discriminatorName = "$type";

        string friendlyId = abstractType.FriendlyId();
        if (!schemaRegistry.Definitions.TryGetValue(friendlyId, out Schema parentSchema))
            parentSchema = schemaRegistry.GetOrRegister(abstractType);

        // set up a discriminator property (it must be required)
        parentSchema.Discriminator = discriminatorName;
        parentSchema.Required = new List<string> { discriminatorName };

        if (parentSchema.Properties == null)
            parentSchema.Properties = new Dictionary<string, Schema>();

        if (!parentSchema.Properties.ContainsKey(discriminatorName))
            parentSchema.Properties.Add(discriminatorName, new Schema { Type = "string", Default = abstractType.FullName });

        // register all subclasses
        var derivedTypes = abstractType.GetTypeInfo().Assembly.GetTypes()
            .Where(x => abstractType != x && abstractType.IsAssignableFrom(x));

        foreach (var item in derivedTypes)
            schemaRegistry.GetOrRegister(item);
    }
}

public class PolymorphismSchemaFilter<T> : ISchemaFilter
{
    private readonly Lazy<HashSet<Type>> derivedTypes = new Lazy<HashSet<Type>>(Init);

    public void Apply(Schema schema, SchemaFilterContext context)
    {
        if (!derivedTypes.Value.Contains(context.SystemType)) return;

        var type = context.SystemType;
        var clonedSchema = new Schema
        {
            Properties = schema.Properties,
            Type = schema.Type,
            Required = schema.Required
        };

        // schemaRegistry.Definitions[typeof(T).Name]; does not work correctly in Swashbuckle.AspNetCore
        var parentSchema = new Schema { Ref = "#/definitions/" + typeof(T).Name };

        var assemblyName = Assembly.GetAssembly(type).GetName();
        schema.Discriminator = "$type";
        // This is required if you use Microsoft's AutoRest client to generate the JavaScript/TypeScript models
        schema.Extensions.Add("x-ms-discriminator-value", $"{type.FullName}, {assemblyName.Name}");
        schema.AllOf = new List<Schema> { parentSchema, clonedSchema };

        // reset properties for they are included in allOf, should be null but code does not handle it
        schema.Properties = new Dictionary<string, Schema>();
    }

    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;
    }
}
Run Code Online (Sandbox Code Playgroud)

需要两个过滤器.第一个将所有已交付的类添加到架构中.它还将基类中不存在的属性添加到派生类型的模式中.

第二个过滤器添加了一些属性($type用于模型返回时的序列化)和扩展(用于Microsoft的AutoRest客户端/生成器)以及向allOfSwagger模式添加属性,这些属性是为了在使用swagger生成时创建继承模式所必需的 - gen或AutoRest.

注册类似,只需要成对注册(只需要注册基类)

// The following lines add polymorphism to the swagger.json schema, so that
// code generators can create properly inheritance hierarchies.
options.DocumentFilter<PolymorphismDocumentFilter<BaseClass>>();
options.SchemaFilter<PolymorphismSchemaFilter<BaseClass>>();
Run Code Online (Sandbox Code Playgroud)