Skip to content

Commit

Permalink
Support DefaultValueAttribute on parameter-based schemas
Browse files Browse the repository at this point in the history
  • Loading branch information
rmorris committed Mar 6, 2021
1 parent 494f15f commit c9eb9dd
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
Expand Up @@ -112,13 +112,19 @@ private OpenApiSchema GenerateSchemaForParameter(ParameterInfo parameterInfo, Sc

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

var defaultValue = parameterInfo.HasDefaultValue
? parameterInfo.DefaultValue
: customAttributes.OfType<DefaultValueAttribute>().FirstOrDefault()?.Value;

if (defaultValue != null)
{
var defaultAsJson = dataContract.JsonConverter(parameterInfo.DefaultValue);
var defaultAsJson = dataContract.JsonConverter(defaultValue);
schema.Default = OpenApiAnyFactory.CreateFromJson(defaultAsJson);
}

schema.ApplyValidationAttributes(parameterInfo.GetCustomAttributes());
schema.ApplyValidationAttributes(customAttributes);

ApplyFilters(schema, parameterInfo.ParameterType, schemaRepository, parameterInfo: parameterInfo);
}
Expand Down
Expand Up @@ -12,7 +12,6 @@
using Xunit;
using Swashbuckle.AspNetCore.TestSupport;
using Microsoft.OpenApi.Any;
using System.Collections.ObjectModel;

namespace Swashbuckle.AspNetCore.SwaggerGen.Test
{
Expand Down Expand Up @@ -334,6 +333,22 @@ public void GenerateSchema_SetsReadOnlyAndWriteOnlyFlags_IfPropertyIsRestricted(
Assert.True(schema.Properties["WriteOnlyProperty"].WriteOnly);
}

[Fact]
public void GenerateSchema_SetsDefault_IfParameterHasDefaultValueAttribute()
{
var schemaRepository = new SchemaRepository();

var parameterInfo = typeof(FakeController)
.GetMethod(nameof(FakeController.ActionWithIntParameterWithDefaultValueAttribute))
.GetParameters()
.First();

var schema = Subject().GenerateSchema(parameterInfo.ParameterType, schemaRepository, parameterInfo: parameterInfo);

Assert.NotNull(schema.Default);
Assert.Equal("3", schema.Default.ToJson());
}

[Theory]
[InlineData(typeof(ComplexType), typeof(ComplexType), "string")]
[InlineData(typeof(GenericType<int, string>), typeof(GenericType<int, string>), "string")]
Expand Down

0 comments on commit c9eb9dd

Please sign in to comment.