Skip to content

Minimal API Validation should respect [JsonPropertyName] #63290

@martincostello

Description

@martincostello

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

Related to #61764.

If a parameter bound to a Minimal API endpoint from the request body uses explicit [JsonPropertyName] attributes to control serialization, this value is not used to generate responses when validation fails.

Name: correspondingProperty.Name,
DisplayName: parameter.GetDisplayName(wellKnownTypes.Get(WellKnownTypeData.WellKnownType.System_ComponentModel_DataAnnotations_DisplayAttribute)) ??
correspondingProperty.GetDisplayName(wellKnownTypes.Get(WellKnownTypeData.WellKnownType.System_ComponentModel_DataAnnotations_DisplayAttribute)),

For example a model property such as this:

[JsonPropertyName("plaintext")]
[Required]
public string Plaintext { get; set; } = string.Empty;

Generates an error such as the below when absent from a request:

{
  "title": "One or more validation errors occurred.",
  "errors": {
    "Plaintext": [
      "The Plaintext field is required."
    ]
  }
}

It's possible to override the value in the message using [Display] (at the cost of additional duplication), but it isn't possible to override the error property name:

+ [Display(Name = "plaintext")]
  [JsonPropertyName("plaintext")]
  [Required]
  public string Plaintext { get; set; } = string.Empty;

Expected Behavior

The Name value of [JsonPropertyName] is used as the default for the Name and DisplayName values if not overridden by [Display] (or some other mechanism that should take precedence) to generate a response like the following:

{
  "title": "One or more validation errors occurred.",
  "errors": {
    "plaintext": [
      "The plaintext field is required."
    ]
  }
}

Steps To Reproduce

  1. Clone martincostello/api@5891d85
  2. Run build.ps1 in the root of the repository.

Exceptions (if any)

No response

.NET Version

10.0.100-preview.7.25380.108

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-minimalIncludes minimal APIs, endpoint filters, parameter binding, request delegate generator etcfeature-validationIssues related to model validation in minimal and controller-based APIs

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions