The Wayback Machine - https://web.archive.org/web/20211120210104/https://github.com/dotnet/aspnetcore/issues/38548
Skip to content
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

Model validation for non-nullable array elements #38548

Open
pmaga opened this issue Nov 20, 2021 · 0 comments
Open

Model validation for non-nullable array elements #38548

pmaga opened this issue Nov 20, 2021 · 0 comments

Comments

@pmaga
Copy link

@pmaga pmaga commented Nov 20, 2021

Non-nullable reference types get implicit [Required] attribute, but this attribute does not work with array elements.

In ASP.NET Core documentation we see this statement:
The validation system treats non-nullable parameters or bound properties as if they had a [Required(AllowEmptyStrings = true)] attribute. By enabling Nullable contexts, MVC implicitly starts validating non-nullable properties or parameters as if they had been attributed with the [Required(AllowEmptyStrings = true)] attribute.

It's awesome, but it's not enough to guarantee valid state in a nullable context.

To Reproduce

<nullable>enabled</nullable>
SuppressImplicitRequiredAttributeForNonNullableReferenceTypes flag is disabled by default:
services.AddControllers(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = false);

Let's take the following example:

public class Request
{
    public List<string> Strings { get; set; }
}
[HttpPost("test")]
public IActionResult Test(Request command)
{
    var isValid = ModelState.IsValid; // returns true
    return Ok();
}

Payload:

{
  "Strings": [
    null
  ]
}

In result, there is no validation error, response status is 200 OK, and we have a null item in the array of not-nullable elements.

Further technical details

  • ASP.NET Core version: 6.0.0

It's very nice that there is such a default behavior, but since it is enabled by default, I would like to trust with full confidence that it will work in any case.
Do you have a plan to improve this validation? This is the typical entry point to an application and it is strange that there is such a flaw in this simple use case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
1 participant