Skip to content

Commit 0e8360e

Browse files
authored
Update optionality check in API descriptor
1 parent ecfd6f5 commit 0e8360e

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

src/Mvc/Mvc.ApiExplorer/src/EndpointMetadataApiDescriptionProvider.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ private ApiDescription CreateApiDescription(RouteEndpoint routeEndpoint, string
143143

144144
// Determine the "requiredness" based on nullability, default value or if allowEmpty is set
145145
var nullability = NullabilityContext.Create(parameter);
146-
var isOptional = parameter.HasDefaultValue || nullability.ReadState == NullabilityState.Nullable || allowEmpty;
146+
var isOptional = parameter.HasDefaultValue || nullability.ReadState != NullabilityState.NotNull || allowEmpty;
147147

148148
return new ApiParameterDescription
149149
{

src/Mvc/Mvc.ApiExplorer/test/EndpointMetadataApiDescriptionProviderTest.cs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,27 @@ public void AddsMetadataFromRouteEndpoint()
413413
Assert.True(apiExplorerSettings.IgnoreApi);
414414
}
415415

416+
[Fact]
417+
public void TestParameterIsRequiredForObliviousNullabilityContext()
418+
{
419+
// In an oblivious nullability context, reference type parameters without
420+
// annotations are optional. Value type parameters are always required.
421+
var apiDescription = GetApiDescription((string foo, int bar) => { });
422+
Assert.Equal(2, apiDescription.ParameterDescriptions.Count);
423+
424+
var fooParam = apiDescription.ParameterDescriptions[0];
425+
Assert.Equal(typeof(string), fooParam.Type);
426+
Assert.Equal(typeof(string), fooParam.ModelMetadata.ModelType);
427+
Assert.Equal(BindingSource.Query, fooParam.Source);
428+
Assert.False(fooParam.IsRequired);
429+
430+
var barParam = apiDescription.ParameterDescriptions[1];
431+
Assert.Equal(typeof(int), barParam.Type);
432+
Assert.Equal(typeof(int), barParam.ModelMetadata.ModelType);
433+
Assert.Equal(BindingSource.Query, barParam.Source);
434+
Assert.True(barParam.IsRequired);
435+
}
436+
416437
[Fact]
417438
public void RespectsProducesProblemExtensionMethod()
418439
{

0 commit comments

Comments
 (0)