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

编程入门 行业动态 更新时间:2024-10-10 21:22:20
本文介绍了在没有ASP.NET模型验证的情况下,如何在Swagger中标记所需的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在创建使用多个私有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中标记所需的属性?

本文发布于:2023-11-07 15:48:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1566862.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:所需   标记   属性   情况下   模型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!