Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Configure non-nullable types as required #2803

Merged
merged 16 commits into from
Jul 23, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
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
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ private void DeepCopy(SchemaGeneratorOptions source, SchemaGeneratorOptions targ
target.DiscriminatorValueSelector = source.DiscriminatorValueSelector;
target.UseAllOfToExtendReferenceSchemas = source.UseAllOfToExtendReferenceSchemas;
target.SupportNonNullableReferenceTypes = source.SupportNonNullableReferenceTypes;
target.MarkNonNullableReferenceTypesAsRequired = source.MarkNonNullableReferenceTypesAsRequired;
target.SchemaFilters = new List<ISchemaFilter>(source.SchemaFilters);
}

Expand All @@ -50,4 +51,4 @@ private TFilter CreateFilter<TFilter>(FilterDescriptor filterDescriptor)
.CreateInstance(_serviceProvider, filterDescriptor.Type, filterDescriptor.Arguments);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,15 @@ public static void SupportNonNullableReferenceTypes(this SwaggerGenOptions swagg
swaggerGenOptions.SchemaGeneratorOptions.SupportNonNullableReferenceTypes = true;
}

/// <summary>
/// Enable detection of non nullable reference types to set Required flag accordingly on schema properties
AntiGuideAkquinet marked this conversation as resolved.
Show resolved Hide resolved
/// </summary>
/// <param name="swaggerGenOptions"></param>
public static void MarkNonNullableReferenceTypesAsRequired(this SwaggerGenOptions swaggerGenOptions)
{
swaggerGenOptions.SchemaGeneratorOptions.MarkNonNullableReferenceTypesAsRequired = true;
}

/// <summary>
/// Automatically infer security schemes from authentication/authorization state in ASP.NET Core.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,21 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.OpenApi.Models;
using Microsoft.Extensions.Options;

namespace Swashbuckle.AspNetCore.SwaggerGen
{
public class SchemaGenerator : ISchemaGenerator
{
private readonly SchemaGeneratorOptions _generatorOptions;
private readonly ISerializerDataContractResolver _serializerDataContractResolver;
private readonly IOptions<MvcOptions> _mvcOptions;

public SchemaGenerator(SchemaGeneratorOptions generatorOptions, ISerializerDataContractResolver serializerDataContractResolver)
public SchemaGenerator(SchemaGeneratorOptions generatorOptions, ISerializerDataContractResolver serializerDataContractResolver, IOptions<MvcOptions> mvcOptions)
AntiGuideAkquinet marked this conversation as resolved.
Show resolved Hide resolved
{
_generatorOptions = generatorOptions;
_serializerDataContractResolver = serializerDataContractResolver;
_mvcOptions = mvcOptions;
}

public OpenApiSchema GenerateSchema(
Expand Down Expand Up @@ -392,7 +395,16 @@ private OpenApiSchema CreateObjectSchema(DataContract dataContract, SchemaReposi
? GenerateSchemaForMember(dataProperty.MemberType, schemaRepository, dataProperty.MemberInfo, dataProperty)
: GenerateSchemaForType(dataProperty.MemberType, schemaRepository);

if ((dataProperty.IsRequired || customAttributes.OfType<RequiredAttribute>().Any())
var markNonNullableTypeAsRequired = (dataProperty.MemberInfo?.IsNonNullableReferenceType() ?? false)
martincostello marked this conversation as resolved.
Show resolved Hide resolved
&& _generatorOptions.MarkNonNullableReferenceTypesAsRequired
#if !NETSTANDARD2_0
&& !_mvcOptions.Value.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes
#endif
;

if ((dataProperty.IsRequired
|| customAttributes.OfType<RequiredAttribute>().Any()
|| markNonNullableTypeAsRequired)
AntiGuideAkquinet marked this conversation as resolved.
Show resolved Hide resolved
&& !schema.Required.Contains(dataProperty.Name))
{
schema.Required.Add(dataProperty.Name);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ public SchemaGeneratorOptions()

public bool SupportNonNullableReferenceTypes { get; set; }

public bool MarkNonNullableReferenceTypesAsRequired { get; set; }
AntiGuideAkquinet marked this conversation as resolved.
Show resolved Hide resolved

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

private string DefaultSchemaIdSelector(Type modelType)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.OpenApi.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Swashbuckle.AspNetCore.SwaggerGen;
using Xunit;

Expand Down Expand Up @@ -75,7 +77,7 @@ public void Apply_EnrichesResponseMetadata_IfActionDecoratedWithSwaggerResponseC
.GetMethod(nameof(FakeControllerWithSwaggerAnnotations.ActionWithSwaggerResponseContentTypesAttributes));
var filterContext = new OperationFilterContext(
apiDescription: null,
schemaRegistry: new SchemaGenerator(new SchemaGeneratorOptions(), new JsonSerializerDataContractResolver(new JsonSerializerOptions())),
schemaRegistry: new SchemaGenerator(new SchemaGeneratorOptions(), new JsonSerializerDataContractResolver(new JsonSerializerOptions()), Options.Create<MvcOptions>(new MvcOptions())),
schemaRepository: new SchemaRepository(),
methodInfo: methodInfo);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.NewtonsoftJson;
using Microsoft.OpenApi.Models;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
Expand Down Expand Up @@ -837,7 +838,7 @@ private static SchemaGenerator Subject(
var serializerSettings = new JsonSerializerSettings();
configureSerializer?.Invoke(serializerSettings);

return new SchemaGenerator(generatorOptions, new NewtonsoftDataContractResolver(serializerSettings));
return new SchemaGenerator(generatorOptions, new NewtonsoftDataContractResolver(serializerSettings), Options.Create<MvcOptions>(new MvcOptions()));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Routing.Constraints;
using Microsoft.OpenApi.Models;
using Microsoft.Extensions.Options;
using Xunit;
using Swashbuckle.AspNetCore.TestSupport;
using Microsoft.OpenApi.Any;
Expand Down Expand Up @@ -637,6 +638,26 @@ public void GenerateSchema_SupportsOption_SupportNonNullableReferenceTypesInDict
Assert.Equal(expectedNullable, propertySchema.Nullable);
}

[Theory]
[InlineData(typeof(TypeWithNullableContext), nameof(TypeWithNullableContext.SubTypeWithOneNullableContent), nameof(TypeWithNullableContext.NullableString), false)]
[InlineData(typeof(TypeWithNullableContext), nameof(TypeWithNullableContext.SubTypeWithOneNonNullableContent), nameof(TypeWithNullableContext.NonNullableString), true)]
public void GenerateSchema_SupportsOption_MarkNonNullableReferenceTypesAsRequired_RequiredAttribute_Compiler_Optimizations_Situations(
Type declaringType,
string subType,
string propertyName,
bool required)
{
var subject = Subject(
configureGenerator: c => c.MarkNonNullableReferenceTypesAsRequired = true
);
var schemaRepository = new SchemaRepository();

subject.GenerateSchema(declaringType, schemaRepository);

var propertyIsRequired = schemaRepository.Schemas[subType].Required.Contains(propertyName);
Assert.Equal(required, propertyIsRequired);
}

[Fact]
public void GenerateSchema_HandlesTypesWithNestedTypes()
{
Expand Down Expand Up @@ -870,7 +891,7 @@ private static SchemaGenerator Subject(
var serializerOptions = new JsonSerializerOptions();
configureSerializer?.Invoke(serializerOptions);

return new SchemaGenerator(generatorOptions, new JsonSerializerDataContractResolver(serializerOptions));
return new SchemaGenerator(generatorOptions, new JsonSerializerDataContractResolver(serializerOptions), Options.Create<MvcOptions>(new MvcOptions()));
AntiGuideAkquinet marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Microsoft.Extensions.Options;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.TestSupport;
using Xunit;
Expand Down Expand Up @@ -1335,7 +1337,7 @@ private static SwaggerGenerator Subject(
return new SwaggerGenerator(
options ?? DefaultOptions,
new FakeApiDescriptionGroupCollectionProvider(apiDescriptions),
new SchemaGenerator(new SchemaGeneratorOptions(), new JsonSerializerDataContractResolver(new JsonSerializerOptions())),
new SchemaGenerator(new SchemaGeneratorOptions(), new JsonSerializerDataContractResolver(new JsonSerializerOptions()), Options.Create<MvcOptions>(new MvcOptions())),
new FakeAuthenticationSchemeProvider(authenticationSchemes ?? Enumerable.Empty<AuthenticationScheme>())
);
}
Expand Down
Loading