如何在 Swagger 中根据需要标记属性,无需 ASP.NET 模型验证? [英] How to mark a property as required in Swagger, without ASP.NET model validation?

查看:12
本文介绍了如何在 Swagger 中根据需要标记属性,无需 ASP.NET 模型验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个使用多个私有 API 的公共 API(无法从外部访问).已经为私有 API 编写了业务验证,我不想为公共 API 重新编写它们.但我确实希望招摇的文档是一样的.

I am creating a public API that uses multiple private APIs (can not be accessed from outside). Business validations have been written for the private APIs and I do not want to re-write them for the public API. But I do want the swagger documentation to be the same.

这就是为什么我想知道是否可以在不使用 ASP.NET 的Required 属性的情况下将属性标记为必需属性.但是招摇的文档表明它是强制性的.这可能吗?

That is why I wonder if I can mark property as mandatory, without using the Required attribute of ASP.NET. But that the swagger documentation indicates that it is mandatory. Is this possible?

推荐答案

感谢 Mohsin,我解决了我的问题.下面我想出了,我创建了一个名为 SwaggerRequired 的属性.该属性可以放置在任何模型上.然后 AddSwaggerRequiredSchemaFilter 确保修改 Swagger 文档.请参阅下面我为此编写的代码

Thanks to Mohsin, I solved my problem. The following I came up with, I created an attribute called SwaggerRequired. This attribute can be placed on any model. The AddSwaggerRequiredSchemaFilter then ensures that the Swagger documentation is modified. See below the code I wrote for this

随机模型:

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

SwaggerRequiredAttribute:

The SwaggerRequiredAttribute:

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

还有 AddSwaggerRequiredSchemaFilter 让它工作:

And the AddSwaggerRequiredSchemaFilter to get it working:

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);
                }
            }
        }
    }
}

这篇关于如何在 Swagger 中根据需要标记属性,无需 ASP.NET 模型验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆