Home > other >  Array creates validation error in ASP.NET 6
Array creates validation error in ASP.NET 6

Time:03-21

I noticed a validation error when changing my WebApi project to use .NET 6 instead of .NET Core 3.1 for my array query parameter types. Previously they didn't return a validation error, but with 6.0 they do.

I have the following class for a query:

public class Query
{
    public List<string> Id { get; set; }
}

And a controller with the following endpoint:

[HttpGet()]
public IActionResult Get([FromQuery] Test2 test)
{
    return Ok()
}

When I send a query without any query parameters, I get a BadRequest marking the field id as required, when implemented using .NET 6. When using .NET Core 3.1 (or 5.0), the method executes correctly.

For reproduction I have created an ASP.NET Core WebApi project both with .NET Core 3.1, 5.0 and 6.0 and added a controller endpoint with a Query-Entity containing a string array as in the example above without any other changes.

Frankly I'm a bit stumped with this one. I tried to execute the Validator for the System.ComponentModel manually, but this yielded in the expected result (no error). I didn't add anything to the scaffold which would account for this behavior, it's basically identical. I didn't find any mention of this in the list of breaking changes for .NET 6.0 as well.

Adding a custom Validation Attribute ("NotRequired") to the Id property fixes the behavior, I would however prefer to be able to keep the query model as-is as it worked previously and the ComponentModel doesn't show any errors.

CodePudding user response:

From the docs:

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.

You can make the property to be nullable reference type so it will make Id optional:

public class Query
{
    public List<string>? Id { get; set; }
}

Or you can completely disable nullable context analysis which will also revert to the old behaviour (so personally I would recommend against it).

  • Related