JsonIgnore 属性在 ASP.NET Core 3 中保持序列化属性

mat*_*lto 7 c# json json.net asp.net-core asp.net-core-3.0

我最近将我的 API 项目更新为 ASP.NET Core 3。从那时起,[JsonIgnore]属性不起作用:

public class Diagnostico
{
    [JsonIgnore]
    public int TipoDiagnostico { get; set; }

    [JsonIgnore]
    public int Orden { get; set; }

    [JsonIgnore]
    public DateTime? FechaInicio { get; set; }

    public string TipoCodificacion { get; set; }

    public string Codigo { get; set; }

    public string Descripcion { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

类的所有属性都被序列化。API 端点在 .NET Core 3 中,但所有逻辑都在 .NET Standard 2.1 中。我意识到序列化程序已从 更改Newtonsoft.JsonSystem.Text.Json。此包在 .NET Standard 2.1 中不可用(它仅适用于 .NET Core),因此要[JsonIgnore]在我正在使用的 .NET Standard 项目中的模型中使用Newtonsoft.Json

Tse*_*eng 12

[JsonIgnore]是一个 JSON.NET 属性,不会被新的System.Text.Json序列化程序使用。

由于您的应用程序是 ASP.NET Core 3.0,因此System.Text.Json将默认使用。如果要继续使用 JSON.NET 注释,则必须在 ASP.NET Core 3 中使用 JSON.NET

就像添加.AddNewtonsoftJson()到您的 MVC 或 WebApi Builder一样简单

services.AddMvc()
    .AddNewtonsoftJson();
Run Code Online (Sandbox Code Playgroud)

或者

services.AddControllers()
    .AddNewtonsoftJson();
Run Code Online (Sandbox Code Playgroud)

用于 WebAPI 风格的应用程序。

  • 好吧,即使您可能将 AddNewtonsoftJson() 作为一种方法,但如果您没有显式地将 Microsoft.AspNetCore.Mvc.NewtonsoftJson nuget 添加到您的项目中,它也是无用的。花了一个小时才发现这个! (6认同)
  • System.Text.Json 也有自己内置的 JsonIgnoreAttribute,具有相同的类名。https://docs.microsoft.com/en-us/dotnet/api/system.text.json.serialization.jsonignoreattribute?view=netcore-3.1 也可在 nuget https://www.nuget.org/packages/System 中使用.Text.Json (2认同)