[DataAnnotations的显示(值)-Swashbuckle-Swagger页面

问题描述 投票:1回答:1

是否可以在Swagger页面上显示参数的DataAnnotations,例如最大值和最小值?

我已经尝试将ShowExtensions和ShowCommonExtension设置为true或调用ShowExtensions(),但这不能解决问题。范围属性和/或Swagger页面上不显示字符串的MaxLength(20)。

启动(代码段)

    app.UseSwaggerUI(
        options =>
        {
            options.ConfigObject = new ConfigObject
            {
                ShowCommonExtensions = true,
                ShowExtensions = true
            };

            options.ConfigObject.AdditionalItems.Add("showCommonExtensions", true);

            options.ShowExtensions();

Framework / Packages

  • 。NET Core 3.1
  • Swashbuckle.AspNetCore(5.4.1)
  • Swashbuckle.AspNetCore.SwaggerGen(5.4.1)

控制器(代码段)

 [HttpGet]
 public IEnumerable<string> GetMethod([Required] [Range(1, 10)] int value)
 {

Swagger UI

Swagger UI

asp.net-core swagger swagger-ui swashbuckle swashbuckle.aspnetcore
1个回答
0
投票

我做了更多的挖掘...

他们确实检查了多个属性:

https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/316ddd0fe6768f470c274a0e93c789b65cf658b9/src/Swashbuckle.AspNetCore.SwaggerGen/SchemaGenerator/OpenApiSchemaExtensions.cs#L12

if (attribute is DefaultValueAttribute defaultValue && defaultValue.Value != null)
{
    schema.Default = OpenApiAnyFactory.CreateFor(schema, defaultValue.Value);
}
else if (attribute is RegularExpressionAttribute regex)
{
    schema.Pattern = regex.Pattern;
}
else if (attribute is RangeAttribute range)
{
    schema.Maximum = decimal.TryParse(range.Maximum.ToString(), out decimal maximum)
        ? maximum
        : schema.Maximum;

    schema.Minimum = decimal.TryParse(range.Minimum.ToString(), out decimal minimum)
        ? minimum
        : schema.Minimum;
}

但是我看到的唯一使用范围的UnitTest在模型上:

https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/47684caeeaaeb4d887236e61a2ea35e4dc76b958/test/Swashbuckle.AspNetCore.TestSupport/Fixtures/DataAnnotatedViaMetadataType.cs#L26

    public class MetadataType
    {
        [Required]
        public string StringWithRequired { get; set; }

        [Required]
        public int IntWithRequired { get; set; }

        [Range(1, 12)]
        public int IntWithRange { get; set; }

        [RegularExpression("^[3-6]?\\d{12,15}$")]
        public string StringWithRegularExpression { get; set; }
    }

如果这是您真正关心的事情,请填写错误报告:https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/new

© www.soinside.com 2019 - 2024. All rights reserved.