简体   繁体   中英

Handling empty subclasses in API calls in ASP.NET Core with .NET 6

I've just upgraded my backend API to ASP.NET Core with .NET 6 and started getting errors if a POST call contains an empty subsclass.

Here's an example. My API receives POST calls for comment entries and the class that handles these calls looks like this:

public class CommentEntry
{
   [Required]
   public string Comments { get; set; }

   public DateTime EntryDate { get; set; }

   public File Attachment { get; set; }
}

As you can see, this class has a File subclass for attachments. The File class looks like this:

public class File
{
   public Guid Id { get; set; }

   public string Name { get; set; }

   public string Url { get; set; }
}

When my API was running ASP.NET Core with .NET 5, I could send a POST request like the one below which sent an empty object for attachment property and it would work fine:

{
   "comments": "Hello World!",
   "entryDate: "2021-11-13T14:52",
   "attachment": {}
}

Now, my controller action method is rejecting this because of !ModelState.IsValid line.

If I change the POST request to the following, it then works in .NET 6 as well.

{
   "comments": "Hello World!",
   "entryDate: "2021-11-13T14:52",
   "attachment: {
      "id": "00000000-0000-0000-0000-000000000000",
      "name": "",
      "url": ""
   }

}

As you can see in CommentEntry class, an attachment is not required.

What's the correct way to handle this scenario where I have no data for the subclass? Should I not be sending an empty object in my POST call?

It seems that the property binding doesn't like 'empty' objects. My guess is that it will try to set the property to null. However, .net 6 has a stricter policy than older frameworks, when it comes to setting things to null.

When you specifically sets a property type to nullable, .net 6 knows that you do it on purpose. In short you should do:

public File? Attachment { get; set; }

so asp.net core knows that null is okay.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM