.NET API end point validating nullable property

  Kiến thức lập trình

In my .NET 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 end point 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 end point on swagger, I receive the following error:

“errors”: {
“ParentFolder.FolderOwner”: [
“The FolderOwner field is required.”
]
}

When testing the end point 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?

LEAVE A COMMENT