In my ASP.NET Core 6 Web API project, I have a FolderDto
type that has a nullable ParentFolder
property:
public class FolderDto
{
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public Folder? ParentFolder { get; set; }
}
I also have an endpoint that receives a FolderDto
:
[HttpPost]
public async Task<Folder> Post([FromBody] FolderDto folderDto)
{
var folder = mapper.Map<Folder>(folderDto);
folder.FolderOwner = folderDto.ParentFolder?.FolderOwner ?? await userService.FindByIdAsync(1);
folderService.CreateFolder(folder);
return folder;
}
When testing this endpoint in Swagger, I get the following error:
"errors": { "ParentFolder.FolderOwner": [ "The FolderOwner field is required." ] }
When testing the endpoint in Swagger, I am intentionally setting the ParentFolder
as an empty object:
{
"name": "string",
"description": "string",
"parentFolder": { }
}
Why is .NET trying to validate a property of the ParentFolder
property when I have set it to be nullable?
You made parentFolder
nullable - which means you can leave out a value for parentFolder
and omit that element from your JSON entirely - or use null
.
But you DID NOT make the actual object it refers to (the parentFolder
's class) all nullable - which means, you CANNOT provide an empty object in your JSON - unless you've made ALL properties of the parentFolder
class nullable.
In short: an empty object is NOT the same thing as or equivalent to null
. It's still an object (with all its properties empty/default/null) - but it's an object - not null
which is no object / nothing / absence of any value