尝试像这样注册一个 ISchemaFilter ,它应该涵盖通用集合和数组:
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
var type = context.Type;
if (type.IsGenericType && type.GetInterface(nameof(IEnumerable)) != null)
{
if (type.GenericTypeArguments.Any(genericTypeArgument => genericTypeArgument.IsValueType))
AddNonNullableFieldToSchema(schema);
}
else if (type.IsArray && type.GetElementType()?.IsValueType == true)
{
AddNonNullableFieldToSchema(schema);
}
}
private static void AddNonNullableFieldToSchema(OpenApiSchema)
{
schema.Items.Extensions["x-nullable"] = new OpenApiBoolean(false);
}