'Why has Newtonsoft [JsonIgnore] stopped working in asp core mvc

Why is my property with a [JsonIgnore] showing in the returned result?

In fact why are all my Newtonsoft attributes not working?

using Newtonsoft.Json;
using System;

namespace Namespace
{
    public class Model
    {
        [JsonIgnore]
        public string IgnoredProperty { get; set; } <-- IS NOT IGNORED
    }
}

Replacing it with IgnoreDataMember or ScriptIgnore doesn't work?



Solution 1:[1]

It's because asp net core has, since Preview 6, changed which default serializer it uses.

Either change it back by adding .AddNewtonsoftJson() to your MVC options.

services.AddControllers().AddNewtonsoftJson()

Or go to your models and start using the System.Text.Json serializer instead.

 using System.Text.Json.Serialization;
 // using Newtonsoft.Json; <- instead of this

Solution 2:[2]

I use Newtonsoft, what worked for me is to use [Newtonsoft.Json.JsonIgnore] before the propeerty to ignore.

Solution 3:[3]

Please Add "System.Text.Json.Serialization" library then It will work fine.

using System;
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;

namespace MyApp.CommonModels
{
    public class PostCommonModel
    {
        public long Id { get; set; }

        [Required]
        public string Title { get; set; }

        [JsonIgnore]
        public string Slug { get; set; }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nathan Cooper
Solution 2 user7221839
Solution 3 Sourav Singh