The problem
All our projects are in .Net Core 2+. Since Microsoft announces end of support for .Net Core 2.2, we have been in the process of upgrading all the projects to the latest .Net Core version. Upgrading to .Net Core 3+ version means that we could use all the new features in C# 8, one of which is the nullable reference types.
After turning on this feature, we start getting reports from developers getting the following runtime validation error
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|752d6065-419d3ab9f0b42013.",
"errors": {
"Something": [
"The Something field is required."
]
}
}
Our tech leads get together and discuss why this happens. We are under the impression that turning on nullable reference types will enforce the rules only during compile time. In Microsoft documentation, it states that (see link here)
The compiler doesn’t add any null checks or other runtime constructs in a nullable context. At runtime, a nullable reference and a non-nullable reference are equivalent
However, they are in fact not equivalent as what we experience after switching it on. We also find in the [Required] attribute documentation something that contradicts the above.
The validation system in .NET Core 3.0 and later treats non-nullable parameters or bound properties as if they had a
[Required]
attribute.
We agree this decision sounded nice at first but it is impractical in reality. This is because we have lots of legacy code which we want to slowly use the new feature without having any runtime exception and having to fix them all at once.
The solution
Turns out we’re not the only ones having this issue and complaining about it when we research for how to get around this issue. This automatic validation check can be turned off in ConfigureServices method in your Startup.cs file. See full documentation here.
services.AddControllers(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);