如何在没有ASP.NET模型验证的情况下,在Swagger中将属性标记为必需的?

z3yyvxxp  于 2023-08-05  发布在  .NET
关注(0)|答案(4)|浏览(99)

我正在创建一个使用多个私有API的公共API(无法从外部访问)。已经为私有API编写了业务验证,我不想为公共API重新编写它们。但我确实希望swagger文档是相同的。
这就是为什么我想知道我是否可以将属性标记为强制性的,而不使用ASP.NET的Required属性。但那份 swagger 的文件表明这是强制性的。这可能吗?

8dtrkrch

8dtrkrch1#

多亏了莫辛,我解决了我的问题。下面是我提出的,我创建了一个名为SwaggerRequired的属性。此属性可以放置在任何模型上。然后,AddSwaggerRequiredSchemaFilter确保修改Swagger文档。下面是我写的代码
随机模型:

public class Foo
{
    [SwaggerRequired]
    public string FooBar{ get; set; }
}

字符串
SwaggerRequiredAttribute:

[AttributeUsage(AttributeTargets.Property)] 
public class SwaggerRequiredAttribute : Attribute
{
}


和AddSwaggerRequiredSchemaFilter来使其工作:

public class AddSwaggerRequiredSchemaFilter : ISchemaFilter
{
    public void Apply(Swashbuckle.Swagger.Schema schema, SchemaRegistry schemaRegistry, Type type)
    {
        PropertyInfo[] properties = type.GetProperties();
        foreach (PropertyInfo property in properties)
        {
            var attribute = property.GetCustomAttribute(typeof(SwaggerRequiredAttribute));

            if (attribute != null)
            {
                var propertyNameInCamelCasing = char.ToLowerInvariant(property.Name[0]) + property.Name.Substring(1);

                if (schema.required == null)
                {
                    schema.required = new List<string>()
                    {
                        propertyNameInCamelCasing
                    };
                }
                else
                {
                    schema.required.Add(propertyNameInCamelCasing);
                }
            }
        }
    }
}

dfuffjeb

dfuffjeb2#

是的,有可能。添加实现IOperationFilter的自定义类

public class UpdateParametersAsRequired : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry s, ApiDescription a)
    {
        if (operation.OperationId == "ControllerName_Action")
        {
            if (operation.Parameters != null)
            {
                foreach (var parameter in operation.Parameters)
                {
                    if (parameter.Name == "ParameterYouWantToEdit")
                    { 
                        // You can edit the properties here
                        parameter.Required = true;
                    }
                }
            }
            else
            {
              // Add parameters if doesn't exists any
                operation.Parameters = new List<IParameter>();
                operation.Parameters.Add(
                    new Parameter
                    {
                        name = "ParameterName",
                        @in = "body",
                        @default = "123",
                        type = "string",
                        description = "x y z",
                        required = true
                    }
                );
            }
        }
    }
}

字符串
干杯!

but5z9lq

but5z9lq3#

我知道很晚了。但其他人可能会得到帮助。
我们可以在需要的属性上添加[JsonRequired]。此外,添加以下代码以抑制验证错误。

[OnError]
    internal void OnError(StreamingContext context, ErrorContext errorContext)
    {
        errorContext.Handled = true;
    }

字符串
总的来说,它会是这样的:

public class Model
    {
        [JsonRequired]
        public Property {get; set;}
        
        [OnError]
        internal void OnError(StreamingContext context, ErrorContext errorContext)
        {
            errorContext.Handled = true;
        }
    }

bn31dyow

bn31dyow4#

C#11 required关键字

使用C#11 required关键字,可以使用以下过滤器轻松转换约束:

public class SwaggerRequiredSchemaFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        if (schema.Properties == null)
        {
            return;
        }

        var properties = context.Type.GetProperties();

        foreach (var schemProp in schema.Properties)
        {
            var codeProp =
                properties.SingleOrDefault(x => x.Name.ToCamelCase() == schemProp.Key)
                ?? throw new MissingFieldException(
                    $"Could not find property {schemProp.Key} in {context.Type}, or several names conflict."
                );

            var isRequired = Attribute.IsDefined(codeProp, typeof(RequiredMemberAttribute));
            if (isRequired)
            {
                schemProp.Value.Nullable = false;
                _ = schema.Required.Add(schemProp.Key);
            }
        }
    }
}

字符串

相关问题