ITADN

Add support for `required` keyword in model properties?

#1895Closedbkoelman 创建于 2025-12-30
enhancementbreaking-changeneeds-investigation
B
bkoelmancommented
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: ```c# 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. <img width="1595" height="628" alt="Image" src="https://github.com/user-attachments/assets/d871c3d5-966d-4f5c-b74a-51704568baa9" /> The following model properties were used to create the picture above: ```c# [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.
关闭于 2026-01-31 2 条评论