In ASP.NET Core MVC, why does [Required] on a non-nullable int never fail, while a non-nullable string property fails with no attribute at all?
answer
- Required only detects null
- int defaults to 0
- int? plus [Required]
- implicit Required(AllowEmptyStrings = true)
- SuppressImplicitRequiredAttributeForNonNullableReferenceTypes
basics
~20 s[Required] only detects null, and an int is never null, so a missing value becomes 0 and passes. With nullable reference types enabled, MVC treats a non-nullable string as [Required(AllowEmptyStrings = true)], and empty strings bind as null, so it fails.
solid answer
~40 s`RequiredAttribute` checks for `null`. A non-nullable `int` always has a value: an omitted JSON property deserializes to `0` and an omitted form field leaves `0`, so `[Required]` never fires (posting an empty string instead gives a binding error, "The value '' is invalid."). To make presence mandatory, declare `int?` with `[Required]`, use `[BindRequired]` for form or query values, or mark a JSON property `[JsonRequired]` or C# `required`. The opposite surprise comes from nullable reference types: with `<Nullable>enable</Nullable>`, MVC treats every non-nullable reference-type property or parameter as if it had `[Required(AllowEmptyStrings = true)]`. Because model binding converts empty strings to `null` by default, a blank `string FullName` still fails. Declare `string?` for optional values, or set `MvcOptions.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true`.
go deeper
Remember that [Required] means not null, so value types such as int need int? before [Required] means anything.
Explain the implicit Required(AllowEmptyStrings = true) for non-nullable reference types, the empty-string-to-null conversion, and the option that disables it.
Pick the right presence check per source ([BindRequired] for form and query, [JsonRequired] or required for JSON) and audit models for silent zeros.
Set conventions for nullable annotations on request models so the contract, OpenAPI document and validation agree, and plan the migration of legacy models.
## What `[Required]` actually tests `RequiredAttribute` in `System.ComponentModel.DataAnnotations` fails when the value is **null**, and for strings also when it is empty or whitespace unless `AllowEmptyStrings = true`. It knows nothing about whether the client *sent* a field. That gap explains both traps. ## Trap one: `[Required]` on a value type ```csharp public class MembershipSignUp { [Required] public int Age { get; set; } // never fails [Required] public int? MonthsCommitted { get; set; } // fails when missing } ``` - An `int` cannot be null. When the JSON body omits `age`, System.Text.Json leaves the property at `0`; when a form omits the field, the complex-object binder leaves it at `0`. `[Required]` sees `0`, not `null`, and passes. - The ASP.NET Core documentation says it directly: on the server, a non-nullable field is always valid and the `[Required]` message is never displayed. - A form that posts the field **empty** behaves differently: binding cannot convert `""` to `int` and records "The value '' is invalid." in `ModelState`. That is a binding error, not the `[Required]` message. Ways to really require a value-type input: | Technique | Works for | Effect when missing | |---|---|---| | `int?` plus `[Required]` | form, query, JSON | `[Required]` error with your message | | `[BindRequired]` on the property | form, route, query (value providers) | binding error "A value for the 'Age' parameter or property was not provided." | | `[JsonRequired]` or the C# `required` modifier | JSON bodies via System.Text.Json | deserialization fails and `ModelState` gets the error | `[Range(16, 99)]` on a plain `int` is a quieter safety net: a missing value becomes `0`, which is out of range, so it fails, but with a range message rather than "required". ## Trap two: implicit `[Required]` on non-nullable reference types When a project enables nullable reference types (`<Nullable>enable</Nullable>`), MVC reads the annotations through its metadata provider: 1. A property or parameter declared `string FullName` (no `?`) is treated as if it carried `[Required(AllowEmptyStrings = true)]`. 2. Model binding converts empty strings to `null` by default (`ConvertEmptyStringToNull`), so a blank form field arrives as `null`. 3. The implicit rule therefore fails with the default "The FullName field is required." message, even though no attribute is written. This catches teams who declare `public string MiddleName { get; set; } = "";` for an optional field and then see unexplained 400s. The fixes: - Declare optional values as `string?`; that is what the annotation means. - Add an explicit `[Required(ErrorMessage = "...")]` where you want a custom message on a mandatory field. - Turn the behaviour off globally with `builder.Services.AddControllers(o => o.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);` if a legacy model cannot be annotated yet. ## Putting it together on the sign-up model ```csharp public class MembershipSignUp { public string FullName { get; set; } = ""; // implicitly required public string? Nickname { get; set; } // optional [Required, Range(16, 99)] public int? Age { get; set; } // required and bounded [JsonRequired] public bool AcceptsTerms { get; set; } // JSON must send it } ``` ## What interviewers listen for - That `[Required]` means "not null", not "was sent". - A correct fix for value types (`int?` plus `[Required]`, `[BindRequired]`, or `[JsonRequired]`), matched to the binding source. - The implicit rule for non-nullable reference types, the empty-string-to-null conversion behind it, and the option that suppresses it.
- Why does [BindRequired] not help on a property of a [FromBody] JSON model?`[BindRequired]` is enforced by MVC's value-provider binding (form, route, query). A `[FromBody]` model is deserialized by an input formatter that ignores binding-behaviour attributes, so a missing JSON property is not reported. For JSON, use `[JsonRequired]`, the C# `required` modifier, or `int?` with `[Required]`.
- A blank optional Nickname field keeps failing with "The Nickname field is required."; what is the cause and fix?The property is declared `string Nickname` in a nullable-enabled project, so MVC treats it as `[Required(AllowEmptyStrings = true)]`, and the blank input binds as `null` because empty strings convert to null by default. Declare it `string?`, or, for legacy code, set `SuppressImplicitRequiredAttributeForNonNullableReferenceTypes` on `MvcOptions`.
- [Required] on an int fails when the client leaves the field out.
- Without a [Required] attribute, a non-nullable string property is always optional in MVC.
- AllowEmptyStrings = true lets a blank form field pass the implicit required rule.
- [BindRequired] makes a property of a JSON body mandatory.
- Nullable annotations are compile-time only and never change MVC validation.