Skip to content

Commit

Permalink
Fix issue #2057 related to readonly properties set via constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
rmorris committed Mar 16, 2021
1 parent 68d7ef8 commit 5127d33
Show file tree
Hide file tree
Showing 5 changed files with 30 additions and 17 deletions.
2 changes: 1 addition & 1 deletion src/Directory.Build.props
Expand Up @@ -6,7 +6,7 @@
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<LicenseUrl>https://licenses.nuget.org/MIT</LicenseUrl>
<VersionPrefix>6.1.0</VersionPrefix>
<VersionPrefix>6.1.1</VersionPrefix>
</PropertyGroup>

<ItemGroup>
Expand Down
Expand Up @@ -146,7 +146,13 @@ private IEnumerable<DataProperty> GetDataPropertiesFor(JsonObjectContract jsonOb

var isSetViaConstructor = jsonProperty.DeclaringType != null && jsonProperty.DeclaringType.GetConstructors()
.SelectMany(c => c.GetParameters())
.Any(p => string.Equals(p.Name, jsonProperty.PropertyName, StringComparison.OrdinalIgnoreCase));
.Any(p =>
{
// Newtonsoft supports setting via constructor if either underlying OR JSON names match
return
string.Equals(p.Name, jsonProperty.UnderlyingName, StringComparison.OrdinalIgnoreCase) ||
string.Equals(p.Name, jsonProperty.PropertyName, StringComparison.OrdinalIgnoreCase);
});

jsonProperty.TryGetMemberInfo(out MemberInfo memberInfo);

Expand Down
@@ -0,0 +1,18 @@
using Newtonsoft.Json;

namespace Swashbuckle.AspNetCore.Newtonsoft.Test
{
public class TypeWithPropertiesSetViaConstructor
{
public TypeWithPropertiesSetViaConstructor(int id, string description)
{
Id = id;
Description = description;
}

public int Id { get; }

[JsonProperty("Desc")]
public string Description { get; }
}
}
Expand Up @@ -327,14 +327,15 @@ public void GenerateSchema_SetsReadOnlyAndWriteOnlyFlags_IfPropertyIsRestricted(
}

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

var referenceSchema = Subject().GenerateSchema(typeof(TypeWithPropertySetViaConstructor), schemaRepository);
var referenceSchema = Subject().GenerateSchema(typeof(TypeWithPropertiesSetViaConstructor), schemaRepository);

var schema = schemaRepository.Schemas[referenceSchema.Reference.Id];
Assert.False(schema.Properties["ReadOnlyProperty"].ReadOnly);
Assert.False(schema.Properties["Id"].ReadOnly);
Assert.False(schema.Properties["Desc"].ReadOnly);
}

[Theory]
Expand Down

This file was deleted.

0 comments on commit 5127d33

Please sign in to comment.