Skip to content

[Required] attribute not working for non-nullable value types #28685

@user-xm

Description

@user-xm

Describe the bug

I saw the description of [Required] attribute in the document

The validation system in .NET Core 3.0 and later treats non-nullable parameters or bound properties as if they had a [Required] attribute. Value types such as decimal and int are non-nullable.

I think this applies to reference types and value types, but it not working for value types.

To Reproduce

#nullable enable
    public class ExampleClass
    {
        public int IntA { get; set; }
        public string StringB { get; set; }
    }

    [ApiController]
    [Route("[controller]")]
    public class ExampleController : ControllerBase
    {
        [HttpPost]
        public void Post(ExampleClass input)
        {
        }
    }
#nullable restore

set body {}, request this api.
response is

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "|2ad0b06e-490569cb5d40decd.",
    "errors": {
        "StringB": [
            "The StringB field is required."
        ]
    }
}

IntA is not included in the error message.
Is this a bug or I misunderstood the document?

Exceptions (if any)

Further technical details

  • ASP.NET Core version
    3.1
  • Include the output of dotnet --info

.NET Core SDK(反映任何 global.json):
Version: 3.1.302
Commit: 41faccf259

运行时环境:
OS Name: Windows
OS Version: 10.0.18363
OS Platform: Windows
RID: win10-x64
Base Path: C:\Program Files\dotnet\sdk\3.1.302\

Host (useful for support):
Version: 3.1.6
Commit: 3acd9b0cd1

.NET Core SDKs installed:
3.1.302 [C:\Program Files\dotnet\sdk]

.NET Core runtimes installed:
Microsoft.AspNetCore.All 2.1.20 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All]
Microsoft.AspNetCore.App 2.1.20 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
Microsoft.AspNetCore.App 3.1.6 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
Microsoft.NETCore.App 2.1.20 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
Microsoft.NETCore.App 3.1.6 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
Microsoft.WindowsDesktop.App 3.1.6 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]

To install additional .NET Core runtimes or SDKs:
https://aka.ms/dotnet-download

  • The IDE (VS / VS Code/ VS4Mac) you're running on, and its version

Microsoft Visual Studio Community 2019
版本 16.6.5

Metadata

Metadata

Assignees

No one assigned

    Labels

    ✔️ Resolution: AnsweredResolved because the question asked by the original author has been answered.Status: Resolvedarea-mvcIncludes: MVC, Actions and Controllers, Localization, CORS, most templates

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions