在没有ASP.NET模型验证的情况下,如何在Swagger中标记所需的属性? [英] How to mark a property as required in Swagger, without ASP.NET model validation?
问题描述
我正在创建使用多个私有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);
}
}
}
}
}
这篇关于在没有ASP.NET模型验证的情况下,如何在Swagger中标记所需的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!