JsonIgnore attribute keeps serializing properties in ASP.NET Core 3

让人想犯罪 __ 提交于 2020-02-13 20:37:01

问题


I've recently updated my API project to ASP.NET Core 3. Since then, [JsonIgnore] attributes are not working:

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; }
}

All the properties of classes are being serialized. The API endpoints are in .NET Core 3, but all the logic is in .NET Standard 2.1. I have realized that the serializer has changed from Newtonsoft.Json to System.Text.Json. This package is not available in .NET Standard 2.1 (it only works in .NET Core) so to use [JsonIgnore] in Models inside .NET Standard projects I am using Newtonsoft.Json .


回答1:


[JsonIgnore] is an JSON.NET attribute and won't be used by the new System.Text.Json serializer.

Since your application is an ASP.NET Core 3.0 System.Text.Json will be used by default. If you want to continue to consume the JSON.NET annotations, you have to use JSON.NET in ASP.NET Core 3

It's as easy as adding .AddNewtonsoftJson() to your MVC or WebApi Builder

services.AddMvc()
    .AddNewtonsoftJson();

or

services.AddControllers()
    .AddNewtonsoftJson();

for WebAPI-esque applications.



来源:https://stackoverflow.com/questions/58499339/jsonignore-attribute-keeps-serializing-properties-in-asp-net-core-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!