【问题标题】:JsonConverter and Swashbuckle - Approach for decorating a swaggerJsonConverter 和 Swashbuckle - 装饰招摇的方法
【发布时间】:2020-11-22 09:11:45
【问题描述】:

我正在玩并开发了一个简单的自定义 JsonConverter,它需要一个最小和最大温度,并按如下方式装饰了我的模型类并验证温度是否在该范围内。

[JsonConverter(typeof(TemperatureConverter), 5, 10)]
public int Temperature { get; set; }

这一切都很好,但我想知道在 swashbuckle 生成的 swagger 文件中最好输出正确装饰的方法是什么......就像这样:

name: Temperature
          schema:
            type: integer
            minimum: 5
            maximum: 10

我知道这是一个微不足道的例子,但它更像是将 JsonConverter 与我感兴趣的招摇的一代联系起来的方法。

我目前正在查看 ISchemaFilter,但看不到如何获得装饰属性的转换器类型。

谢谢

【问题讨论】:

  • 你使用 FluentValidation 吗?我能够让 Swashbuckle 使用一个属性(请参阅下面的答案),但我无法让 FluentValidation 使用一个。显然你不能像下面那样做类似的技巧,因为 AbstractValidator 的扩展永远不会被调用,所以你不能做一个主验证器。

标签: json.net asp.net-web-api2 asp.net-core-2.0 asp.net-core-2.1 swashbuckle


【解决方案1】:

您必须处于父架构级别,查看它的属性。当它到达属性本身时,为时已晚,因为没有返回父类的链接。

我使用的是自定义属性,而不是 JsonConverter,但是这样的东西应该可以用于检测属性。

    public class TemperatureSchemaFilter : ISchemaFilter
    {
        public void Apply(Schema schema, SchemaFilterContext context)
        {
            var converterProperties = context.SystemType.GetProperties().Where(
                prop => prop.CustomAttributes.Select(
                    attr => attr.AttributeType == typeof(JsonConverterAttribute)).Any()
                ).ToList();
            foreach (var converterProperty in converterProperties)
            {
                var converterAttribute = (JsonConverterAttribute)Attribute.GetCustomAttribute(converterProperty.PropertyType, typeof(JsonConverterAttribute));
                if (converterAttribute.ConverterType != typeof(TemperatureConverter)) continue;
                Schema propertySchema = null;
                try
                {
                    propertySchema = schema.Properties.First(x => x.Key.ToLower().Equals(converterProperty.Name.ToLower())).Value;
                }
                catch (Exception)
                {
                    continue;
                }

                if (propertySchema == null) continue;
                propertySchema.Minimum = (double) converterAttribute.ConverterParameters[0];
                propertySchema.Maximum = (double) converterAttribute.ConverterParameters[1];
            }
        }
    }

不幸的是,我的环境目前已经被水洗了,所以我无法对其进行测试,但我认为这是要走的路。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-19
    • 2017-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 2019-06-14
    • 1970-01-01
    相关资源
    最近更新 更多