Skip to content

Add support for required keyword in model properties #1895

@bkoelman

Description

@bkoelman

Model properties that use the required keyword (not to be confused with the [Required] attribute) don't always cause a validation failure when creating a new resource.

For example, in the following case, no validation error is produced when the name field does not appear in the POST request body:

public class TestModel : Identifiable<long>
{
    [Attr] public required string? Name { get; set; }
}

Addressing this would also fix the limitation described at https://www.jsonapi.net/usage/common-pitfalls.html#validation-of-required-value-types-doesnt-work.

The picture below shows the impact on JSON:API attributes. How this affects relationships is to be investigated.

Image

The following model properties were used to create the picture above:

[Attr] public string NonNullableString { get; set; } = null!;
[Attr] public required string KeywordRequiredNonNullableString { get; set; }
[Attr] [Required] public string AttributeRequiredNonNullableString { get; set; } = null!;
[Attr] [Required] public required string KeywordAttributeRequiredNonNullableString { get; set; }

[Attr] public string? NullableString { get; set; } = null!;
[Attr] public required string? KeywordRequiredNullableString { get; set; }
[Attr] [Required] public string? AttributeRequiredNullableString { get; set; } = null!;
[Attr] [Required] public required string? KeywordAttributeRequiredNullableString { get; set; }

[Attr] public int NonNullableInt { get; set; }
[Attr] public required int KeywordRequiredNonNullableInt { get; set; }
[Attr] [Required] public int AttributeRequiredNonNullableInt { get; set; }
[Attr] [Required] public required int KeywordAttributeRequiredNonNullableInt { get; set; }

[Attr] public int? NullableInt { get; set; }
[Attr] public required int? KeywordRequiredNullableInt { get; set; }
[Attr] [Required] public int? AttributeRequiredNullableInt { get; set; }
[Attr] [Required] public required int? KeywordAttributeRequiredNullableInt { get; set; }

In this picture, the left-most block shows the behavior of a standard ASP.NET Web API project. The blocks to the right describe the JsonApiDotNetCore behavior for a POST/PATCH resource request. The blue markers indicate where a binding error should be produced (or the OpenAPI output needs to be adjusted) to resolve this issue.

Something to consider is the desired behavior when Model Validation and/or nullable reference types are turned off.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions