在 ASP.NET Core webapp 中使用 Swashbuckle.AspNetCore,我们有如下响应类型:
public class DateRange
{
[JsonConverter(typeof(IsoDateConverter))]
public DateTime StartDate {get; set;}
[JsonConverter(typeof(IsoDateConverter))]
public DateTime EndDate {get; set;}
}
当使用 Swashbuckle 发出 swagger API JSON 时,这变成:
{ ...
"DateRange": {
"type": "object",
"properties": {
"startDate": {
"format": "date-time",
"type": "string"
},
"endDate": {
"format": "date-time",
"type": "string"
}
}
}
...
}
这里的问题是 DateTime
是一个值类型,永远不能为 null;但是发出的 Swagger API JSON 不会将 2 个属性标记为 required
。此行为对于所有其他值类型都是相同的:int、long、byte 等 - 它们都被认为是可选的。
为了完成图片,我们将我们的 Swagger API JSON 提供给 dtsgenerator为 JSON 响应模式生成 typescript 接口(interface)。例如上面的类变为:
export interface DateRange {
startDate?: string; // date-time
endDate?: string; // date-time
}
这显然是不正确的。在稍微深入研究之后,我得出结论,dtsgenerator 在使 typescript 中的非必需属性可为 null 方面做的是正确的。也许 swagger 规范需要对可空与必需的显式支持,但现在这 2 个是混为一谈的。
我知道我可以为每个值类型属性添加一个[Required]
属性,但这跨越多个项目和数百个类,是冗余信息,必须维护.所有不可为 null 的值类型属性都不能为 null,因此将它们表示为可选似乎是不正确的。
Web API、Entity Framework 和 Json.net 都明白值类型属性不能为 null
;因此使用这些库时不需要 [Required]
属性。
我正在寻找一种方法来自动标记我的 swagger JSON 中所需的所有不可为 null 的值类型以匹配此行为。
最佳答案
如果您使用的是 C# 8.0+ 并启用了可空引用类型,那么答案会更简单。假设所有不可为 null 的类型都是必需的并且所有其他明确定义为可为 null 的类型不是可接受的划分,那么以下架构过滤器将起作用。
public class RequireNonNullablePropertiesSchemaFilter : ISchemaFilter
{
/// <summary>
/// Add to model.Required all properties where Nullable is false.
/// </summary>
public void Apply(OpenApiSchema model, SchemaFilterContext context)
{
var additionalRequiredProps = model.Properties
.Where(x => !x.Value.Nullable && !model.Required.Contains(x.Key))
.Select(x => x.Key);
foreach (var propKey in additionalRequiredProps)
{
model.Required.Add(propKey);
}
}
}
Apply 方法将遍历每个模型属性检查以查看 Nullable 是否为 false 并将它们添加到所需对象列表中。根据观察,Swashbuckle 似乎在根据是否为可空类型设置 Nullable 属性方面做得很好。如果您不相信它,您始终可以使用反射来产生相同的效果。
与其他架构过滤器一样,不要忘记在您的 Startup 类中添加这个过滤器以及适当的 Swashbuckle 扩展来处理可为 null 的对象。
services.AddSwaggerGen(c =>
{
/*...*/
c.SchemaFilter<RequireNonNullablePropertiesSchemaFilter>();
c.SupportNonNullableReferenceTypes(); // Sets Nullable flags appropriately.
c.UseAllOfToExtendReferenceSchemas(); // Allows $ref enums to be nullable
c.UseAllOfForInheritance(); // Allows $ref objects to be nullable
}
关于c# - Swashbuckle:使不可为空的属性成为必需的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46576234/