如何忽略 .Net Core Web API 绑定模型的 Class 级别的属性

How to Ignore Properties at the Class Level for .Net Core Web API Bind Model

有没有办法在像 JsonInclude 这样的请求模型中为复杂类型指定包含或排除的属性?我认为必须为每个请求编写一个 POCO 并且必须为每个 POCO 上的每个 属性 添加验证属性将是一场噩梦。

public class RegisterUserRequest
{
    //Ignore all other properties including their requirement attributes
    [JsonInclude("FirstName,LastName,Username,Password")] 
    public User user { get; set; }

    [Required]
    public string PasswordConfirmation { get; set; }
    
    [Required]
    public string Email { get; set; }
}

您可以使用 DefaultContractResolver

给定的两个 link 可以帮助你。

https://www.niceonecode.com/question/20711/newtonsoft-json-ignore-property-dynamically-during-serialization

https://www.newtonsoft.com/json/help/html/conditionalproperties.htm

此外,您可以在给定的 link.

中覆盖基本忽略 属性 when ReadOnly、Empty 等条件

https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-ignore-properties?pivots=dotnet-6-0