Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

MVC JSON Serializer Lifetime?

$
0
0

I noticed some interesting behavior with JSON serialization in which references are preserved. I'm guessing the JSON serializer is set up as a singleton, and therefore its reference resolver is never reset.

I have created the default MVC app in Visual studio, with the following modifications:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddOptions();

            services.Configure<MvcJsonOptions>(options =>
            {
                options.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
            });

            // Add framework services.
            services.AddMvc();
        }
[Route("api/[controller]")]
    public class ValuesController : Controller
    {
        // GET api/values
        [HttpGet]
        public MyValue Get()
        {
            return new MyValue()
            {
                Name = "ABCD"
            };
        }

        public class MyValue
        {
            public string Name { get; set; }
        }
    }


If you hit that controller you see on the first GET:

{"$id": "1","Name": "ABCD"
}

On the second GET:

{"$id": "2","Name": "ABCD"
}

And so on, which leads me to believe it is never resetting its reference resolver. Is this expected behavior, and I am just new to JSON that contains references, or is this an issue that could potentially keep on growing the underlying dictionary that is maintained for JSON reference resolution?


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>