Skip to content

Fixed: ModelState validation failed when [Range] does not include property default value #1253

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

Merged
merged 1 commit into from
Feb 5, 2023
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,7 @@ public JsonApiModelMetadataProvider(ICompositeMetadataDetailsProvider detailsPro
protected override ModelMetadata CreateModelMetadata(DefaultMetadataDetails entry)
{
var metadata = (DefaultModelMetadata)base.CreateModelMetadata(entry);

if (metadata.ValidationMetadata.IsRequired == true)
{
metadata.ValidationMetadata.PropertyValidationFilter = _jsonApiValidationFilter;
}
metadata.ValidationMetadata.PropertyValidationFilter = _jsonApiValidationFilter;

return metadata;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using JsonApiDotNetCore.Middleware;
using JsonApiDotNetCore.Resources;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.Extensions.DependencyInjection;

Expand All @@ -23,15 +24,13 @@ public JsonApiValidationFilter(IHttpContextAccessor httpContextAccessor)
/// <inheritdoc />
public bool ShouldValidateEntry(ValidationEntry entry, ValidationEntry parentEntry)
{
IServiceProvider serviceProvider = GetScopedServiceProvider();

var request = serviceProvider.GetRequiredService<IJsonApiRequest>();

if (IsId(entry.Key))
if (entry.Metadata.MetadataKind == ModelMetadataKind.Type || IsId(entry.Key))
{
return true;
}

IServiceProvider serviceProvider = GetScopedServiceProvider();
var request = serviceProvider.GetRequiredService<IJsonApiRequest>();
bool isTopResourceInPrimaryRequest = string.IsNullOrEmpty(parentEntry.Key) && IsAtPrimaryEndpoint(request);

if (!isTopResourceInPrimaryRequest)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@ internal sealed class ModelStateFakers : FakerContainer
new Faker<SystemFile>()
.UseSeed(GetFakerSeed())
.RuleFor(systemFile => systemFile.FileName, faker => faker.System.FileName())
.RuleFor(systemFile => systemFile.Attributes, faker => faker.Random.Enum(FileAttributes.Normal, FileAttributes.Hidden, FileAttributes.ReadOnly))
.RuleFor(systemFile => systemFile.SizeInBytes, faker => faker.Random.Long(0, 1_000_000)));

private readonly Lazy<Faker<SystemDirectory>> _lazySystemDirectoryFaker = new(() =>
new Faker<SystemDirectory>()
.UseSeed(GetFakerSeed())
.RuleFor(systemDirectory => systemDirectory.Name, faker => faker.Address.City())
.RuleFor(systemDirectory => systemDirectory.IsCaseSensitive, faker => faker.Random.Bool())
.RuleFor(systemDirectory => systemDirectory.SizeInBytes, faker => faker.Random.Long(0, 1_000_000)));
.RuleFor(systemDirectory => systemDirectory.Name, faker => Path.GetFileNameWithoutExtension(faker.System.FileName()))
.RuleFor(systemDirectory => systemDirectory.IsCaseSensitive, faker => faker.Random.Bool()));

public Faker<SystemVolume> SystemVolume => _lazySystemVolumeFaker.Value;
public Faker<SystemFile> SystemFile => _lazySystemFileFaker.Value;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,8 +166,6 @@ public async Task Cannot_create_resource_with_multiple_violations()
type = "systemDirectories",
attributes = new
{
isCaseSensitive = false,
sizeInBytes = -1
}
}
};
Expand All @@ -192,9 +190,9 @@ public async Task Cannot_create_resource_with_multiple_violations()
ErrorObject error2 = responseDocument.Errors[1];
error2.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error2.Title.Should().Be("Input validation failed.");
error2.Detail.Should().Be("The field SizeInBytes must be between 0 and 9223372036854775807.");
error2.Detail.Should().Be("The IsCaseSensitive field is required.");
error2.Source.ShouldNotBeNull();
error2.Source.Pointer.Should().Be("/data/attributes/sizeInBytes");
error2.Source.Pointer.Should().Be("/data/attributes/isCaseSensitive");
}

[Fact]
Expand All @@ -205,15 +203,14 @@ public async Task Does_not_exceed_MaxModelValidationErrors()
{
data = new
{
type = "systemDirectories",
type = "systemFiles",
attributes = new
{
sizeInBytes = -1
}
}
};

const string route = "/systemDirectories";
const string route = "/systemFiles";

// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody);
Expand All @@ -232,16 +229,16 @@ public async Task Does_not_exceed_MaxModelValidationErrors()
ErrorObject error2 = responseDocument.Errors[1];
error2.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error2.Title.Should().Be("Input validation failed.");
error2.Detail.Should().Be("The Name field is required.");
error2.Detail.Should().Be("The FileName field is required.");
error2.Source.ShouldNotBeNull();
error2.Source.Pointer.Should().Be("/data/attributes/directoryName");
error2.Source.Pointer.Should().Be("/data/attributes/fileName");

ErrorObject error3 = responseDocument.Errors[2];
error3.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error3.Title.Should().Be("Input validation failed.");
error3.Detail.Should().Be("The IsCaseSensitive field is required.");
error3.Detail.Should().Be("The Attributes field is required.");
error3.Source.ShouldNotBeNull();
error3.Source.Pointer.Should().Be("/data/attributes/isCaseSensitive");
error3.Source.Pointer.Should().Be("/data/attributes/attributes");
}

[Fact]
Expand Down Expand Up @@ -360,30 +357,30 @@ await _testContext.RunOnDatabaseAsync(async dbContext =>
public async Task Can_update_resource_with_omitted_required_attribute_value()
{
// Arrange
SystemDirectory existingDirectory = _fakers.SystemDirectory.Generate();
SystemFile existingFile = _fakers.SystemFile.Generate();

long newSizeInBytes = _fakers.SystemDirectory.Generate().SizeInBytes;
long? newSizeInBytes = _fakers.SystemFile.Generate().SizeInBytes;

await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Directories.Add(existingDirectory);
dbContext.Files.Add(existingFile);
await dbContext.SaveChangesAsync();
});

var requestBody = new
{
data = new
{
type = "systemDirectories",
id = existingDirectory.StringId,
type = "systemFiles",
id = existingFile.StringId,
attributes = new
{
sizeInBytes = newSizeInBytes
}
}
};

string route = $"/systemDirectories/{existingDirectory.StringId}";
string route = $"/systemFiles/{existingFile.StringId}";

// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,6 @@ public sealed class SystemDirectory : Identifiable<int>
[Required]
public bool? IsCaseSensitive { get; set; }

[Attr]
[Range(typeof(long), "0", "9223372036854775807")]
public long SizeInBytes { get; set; }

[HasMany]
public ICollection<SystemDirectory> Subdirectories { get; set; } = new List<SystemDirectory>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ public sealed class SystemFile : Identifiable<int>

[Attr]
[Required]
[Range(typeof(long), "0", "9223372036854775807")]
public long? SizeInBytes { get; set; }
public FileAttributes? Attributes { get; set; }

[Attr]
[Range(typeof(long), "1", "9223372036854775807")]
public long SizeInBytes { get; set; }
}