Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<UseArtifactsOutput>true</UseArtifactsOutput>
<VersionPrefix>9.0.4</VersionPrefix>
<VersionPrefix>9.1.0</VersionPrefix>
<WarnOnPackingNonPackableProject>false</WarnOnPackingNonPackableProject>
</PropertyGroup>
<PropertyGroup Condition=" '$(GITHUB_ACTIONS)' != '' AND '$(DEPENDABOT_JOB_ID)' == '' ">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,13 @@ public DataContract GetDataContractForType(Type type)
jsonConverter: JsonConverterFunc);
}

var jsonContract = _contractResolver.ResolveContract(effectiveType);
var jsonContract = _contractResolver.ResolveContract(type);

if (jsonContract is JsonPrimitiveContract && !jsonContract.UnderlyingType.IsEnum)
var effectiveUnderlyingType = Nullable.GetUnderlyingType(jsonContract.UnderlyingType) ?? jsonContract.UnderlyingType;

if (jsonContract is JsonPrimitiveContract && !effectiveUnderlyingType.IsEnum)
{
if (!PrimitiveTypesAndFormats.TryGetValue(jsonContract.UnderlyingType, out var primitiveTypeAndFormat))
if (!PrimitiveTypesAndFormats.TryGetValue(effectiveUnderlyingType, out var primitiveTypeAndFormat))
{
primitiveTypeAndFormat = Tuple.Create(DataType.String, (string)null);
}
Expand All @@ -38,16 +40,16 @@ public DataContract GetDataContractForType(Type type)
jsonConverter: JsonConverterFunc);
}

if (jsonContract is JsonPrimitiveContract && jsonContract.UnderlyingType.IsEnum)
if (jsonContract is JsonPrimitiveContract && effectiveUnderlyingType.IsEnum)
{
var enumValues = jsonContract.UnderlyingType.GetEnumValues();
var enumValues = effectiveUnderlyingType.GetEnumValues();

// Test to determine if the serializer will treat as string
var serializeAsString = (enumValues.Length > 0) && JsonConverterFunc(enumValues.GetValue(0)).StartsWith('\"');

var primitiveTypeAndFormat = serializeAsString
? PrimitiveTypesAndFormats[typeof(string)]
: PrimitiveTypesAndFormats[jsonContract.UnderlyingType.GetEnumUnderlyingType()];
: PrimitiveTypesAndFormats[effectiveUnderlyingType.GetEnumUnderlyingType()];

return DataContract.ForPrimitive(
underlyingType: jsonContract.UnderlyingType,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ private static void DeepCopy(SchemaGeneratorOptions source, SchemaGeneratorOptio
target.DiscriminatorNameSelector = source.DiscriminatorNameSelector;
target.DiscriminatorValueSelector = source.DiscriminatorValueSelector;
target.UseAllOfToExtendReferenceSchemas = source.UseAllOfToExtendReferenceSchemas;
target.UseOneOfForNullableEnums = source.UseOneOfForNullableEnums;
target.SupportNonNullableReferenceTypes = source.SupportNonNullableReferenceTypes;
target.NonNullableReferenceTypesAsRequired = source.NonNullableReferenceTypesAsRequired;
target.SchemaFilters = [.. source.SchemaFilters];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,15 @@ public static void UseAllOfToExtendReferenceSchemas(this SwaggerGenOptions swagg
swaggerGenOptions.SchemaGeneratorOptions.UseAllOfToExtendReferenceSchemas = true;
}

/// <summary>
/// Extend enumeration schemas using the <c>oneOf</c> construct to allow <see langword="null"/> when referenced.
/// </summary>
/// <param name="swaggerGenOptions"></param>
public static void UseOneOfForNullableEnums(this SwaggerGenOptions swaggerGenOptions)
{
swaggerGenOptions.SchemaGeneratorOptions.UseOneOfForNullableEnums = true;
}

/// <summary>
/// Enable detection of non nullable reference types to set Nullable flag accordingly on schema properties
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
static Microsoft.Extensions.DependencyInjection.SwaggerGenOptionsExtensions.UseOneOfForNullableEnums(this Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenOptions swaggerGenOptions) -> void
Swashbuckle.AspNetCore.SwaggerGen.SchemaGeneratorOptions.UseOneOfForNullableEnums.get -> bool
Swashbuckle.AspNetCore.SwaggerGen.SchemaGeneratorOptions.UseOneOfForNullableEnums.set -> void
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public DataContract GetDataContractForType(Type type)
primitiveTypeAndFormat = PrimitiveTypesAndFormats[exampleType];

return DataContract.ForPrimitive(
underlyingType: effectiveType,
underlyingType: type,
dataType: primitiveTypeAndFormat.Item1,
dataFormat: primitiveTypeAndFormat.Item2,
jsonConverter: (value) => JsonConverterFunc(value, type));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,18 @@ private OpenApiSchema GenerateSchemaForMember(
MemberInfo memberInfo,
DataProperty dataProperty = null)
{
if (dataProperty != null)
{
var customAttributes = memberInfo.GetInlineAndMetadataAttributes();

var requiredAttribute = customAttributes.OfType<RequiredAttribute>().FirstOrDefault();

if (!IsNullable(requiredAttribute, dataProperty, memberInfo))
{
modelType = Nullable.GetUnderlyingType(modelType) ?? modelType;
}
}

var dataContract = GetDataContractFor(modelType);

var schema = _generatorOptions.UseOneOfForPolymorphism && IsBaseTypeWithKnownTypesDefined(dataContract, out var knownTypesDataContracts)
Expand Down Expand Up @@ -129,6 +141,13 @@ private OpenApiSchema GenerateSchemaForParameter(
ParameterInfo parameterInfo,
ApiParameterRouteInfo routeInfo)
{
var customAttributes = parameterInfo.GetCustomAttributes();

if (customAttributes.OfType<RequiredAttribute>().Any())
{
modelType = Nullable.GetUnderlyingType(modelType) ?? modelType;
}

var dataContract = GetDataContractFor(modelType);

var schema = _generatorOptions.UseOneOfForPolymorphism && IsBaseTypeWithKnownTypesDefined(dataContract, out var knownTypesDataContracts)
Expand All @@ -143,8 +162,6 @@ private OpenApiSchema GenerateSchemaForParameter(

if (schema.Reference == null)
{
var customAttributes = parameterInfo.GetCustomAttributes();

var defaultValue = parameterInfo.HasDefaultValue
? parameterInfo.DefaultValue
: customAttributes.OfType<DefaultValueAttribute>().FirstOrDefault()?.Value;
Expand All @@ -154,6 +171,11 @@ private OpenApiSchema GenerateSchemaForParameter(
schema.Default = GenerateDefaultValue(dataContract, modelType, defaultValue);
}

if (Nullable.GetUnderlyingType(modelType) is not null)
{
schema.Nullable = true;
}

schema.ApplyValidationAttributes(customAttributes);
if (routeInfo != null)
{
Expand Down Expand Up @@ -255,7 +277,7 @@ private OpenApiSchema GenerateConcreteSchema(DataContract dataContract, SchemaRe
case DataType.Number:
case DataType.String:
{
schemaFactory = () => CreatePrimitiveSchema(dataContract);
schemaFactory = () => CreatePrimitiveSchema(dataContract, schemaRepository);
returnAsReference = dataContract.UnderlyingType.IsEnum && !_generatorOptions.UseInlineDefinitionsForEnums;
break;
}
Expand Down Expand Up @@ -301,16 +323,41 @@ private bool TryGetCustomTypeMapping(Type modelType, out Func<OpenApiSchema> sch
(modelType.IsConstructedGenericType && _generatorOptions.CustomTypeMappings.TryGetValue(modelType.GetGenericTypeDefinition(), out schemaFactory));
}

private static OpenApiSchema CreatePrimitiveSchema(DataContract dataContract)
private OpenApiSchema CreatePrimitiveSchema(DataContract dataContract, SchemaRepository schemaRepository)
{
var underlyingType = Nullable.GetUnderlyingType(dataContract.UnderlyingType) ?? dataContract.UnderlyingType;

if (underlyingType.IsEnum && dataContract.UnderlyingType != underlyingType)
{
var enumDataContract = GetDataContractFor(underlyingType);

var enumSchema = GenerateConcreteSchema(enumDataContract, schemaRepository);

if (_generatorOptions.UseInlineDefinitionsForEnums)
{
enumSchema.Enum.Add(null);
return enumSchema;
}

if (_generatorOptions.UseOneOfForNullableEnums)
{
enumSchema.OneOf =
[
new OpenApiSchema { Reference = enumSchema.Reference },
new OpenApiSchema { Enum = [null] }
];
enumSchema.Reference = null;
}

return enumSchema;
}

var schema = new OpenApiSchema
{
Type = FromDataType(dataContract.DataType),
Format = dataContract.DataFormat
};

var underlyingType = dataContract.UnderlyingType;

if (underlyingType.IsEnum)
{
var enumValues = underlyingType.GetEnumValues().Cast<object>();
Expand Down Expand Up @@ -422,7 +469,7 @@ private OpenApiSchema CreateObjectSchema(DataContract dataContract, SchemaReposi
continue;
}

var memberType = dataProperty.MemberType;
var memberType = dataProperty.IsNullable ? dataProperty.MemberType : (Nullable.GetUnderlyingType(dataProperty.MemberType) ?? dataProperty.MemberType);

schema.Properties[dataProperty.Name] = (dataProperty.MemberInfo != null)
? GenerateSchemaForMember(memberType, schemaRepository, dataProperty.MemberInfo, dataProperty)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ public SchemaGeneratorOptions()

public IList<ISchemaFilter> SchemaFilters { get; set; }

/// <summary>
/// Gets or sets a value indicating whether to extend enumeration schemas using the <c>oneOf</c> construct to allow <see langword="null"/> when referenced.
/// </summary>
public bool UseOneOfForNullableEnums { get; set; }

private string DefaultSchemaIdSelector(Type modelType)
{
if (!modelType.IsConstructedGenericType)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -586,7 +586,7 @@ apiParameter.Type is not null &&

var schema = (type != null)
? GenerateSchema(
type,
Nullable.GetUnderlyingType(type) ?? type,
schemaRepository,
apiParameter.PropertyInfo(),
apiParameter.ParameterInfo(),
Expand Down
Loading
Loading