代码之家  ›  专栏  ›  技术社区  ›  Thomas Levesque

如何使用花饰扣.AspNetCore

  •  0
  • Thomas Levesque  · 技术社区  · 6 年前

    我有一个自定义泛型类型,大致如下所示:

    public struct Foo<T>
    {
        public int Value { get; }
        public string Signature { get; }
        public Type Type { get; }
    }
    

    此类型用于请求和响应主体以及控制器操作参数中。所有的配置都是以字符串的形式序列化的,并且可以很好地与模型绑定和JSON序列化配合使用。类型具有 TypeConverter 与它关联,它负责将它转换为字符串和从字符串转换。

    但是,Swagger模式仍然将其表示为具有3个属性的对象。这个 Type System.Reflection 直接或间接暴露的类型 类型 .

    如何避免这种情况并将我的类型公开为字符串?


    MapType

    我试着用 地图类型 ;如果指定泛型类型参数,则可以正常工作,但不能使用打开的泛型类型:

    c.MapType(typeof(Foo<Something>), () => new OpenApiSchema { Type = "string" }); // Works
    c.MapType(typeof(Foo<>), () => new OpenApiSchema { Type = "string" }); // Doesn't work
    

    我可以申请地图吗 Foo<T> ,对于任何 T


    当前解决方案

    class SchemaFilter : ISchemaFilter
    {
        public void Apply(OpenApiSchema schema, SchemaFilterContext context)
        {
            if (context.Type is Type type &&
                type.IsGenericType &&
                !type.IsGenericTypeDefinition &&
                type.GetGenericTypeDefinition() == typeof(Foo<>))
            {
                schema.Type = "string";
                schema.Properties.Clear();
            }
            else if (context.Type?.FullName.StartsWith("System.", StringComparison.Ordinal) is true
                && context.SchemaRepository.TryGetIdFor(context.Type, out var schemaId))
            {
                DocFilter.SchemaIdsToRemove.Add(schemaId);
            }
        }
    }
    
    class DocFilter : IDocumentFilter
    {
        public static readonly HashSet<string> SchemaIdsToRemove = new HashSet<string>();
    
        public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {
            foreach (var schemaId in SchemaIdsToRemove)
            {
                swaggerDoc.Components.Schemas.Remove(schemaId);
            }
        }
    }
    
    0 回复  |  直到 6 年前
    推荐文章