Controller.json set Serialization.ReferenceLoopHandling

Is there a way to set the Controller.Json property ReferenceLoopHandling?

Currently, it causes a cycle of self-regulation when analyzing objects with navigational properties defined at both ends. This problem is solved by installing

ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

Is there a way to do this for the Controller.Json method?

I found this piece of code, but it does not work.

services.Configure<MvcOptions>(option =>
        {
            option.OutputFormatters.Clear();
            var jsonOutputFormatter = new JsonOutputFormatter();
            jsonOutputFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

            option.OutputFormatters.Insert(0, jsonOutputFormatter);
        });
+3
source share
2 answers

I think a nicer solution for this is to add JsonOptions to your ConfigureServices, for example:

services.AddMvc().AddJsonOptions(options =>
{
    options.SerializerSettings.ReferenceLoopHandling = 
                               Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
+7
source

The question is a long time ago, but it can still help other people.

Try in the ConfigureServices method of the Startup class:

services.AddMvc(options =>
{
    ((JsonOutputFormatter)options.OutputFormatters.Single(f => f.GetType() == typeof(JsonOutputFormatter))).SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});

or

services.AddMvc(options =>
{
    var jsonOutputFormatter = options.OutputFormatters.SingleOrDefault(f => f.GetType() == typeof(JsonOutputFormatter)) as JsonOutputFormatter;
    if (jsonOutputFormatter != null)
        jsonOutputFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
+2

All Articles