8

is there a way to set Controller.Json ReferenceLoopHandling property?

It is currently causing a self referencing loop when parsing entities with navigation properties defined on both ends. This problem is solved by setting

ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

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

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

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

            option.OutputFormatters.Insert(0, jsonOutputFormatter);
        });
Ivan Rep
  • 369
  • 5
  • 8

3 Answers3

15

I think that a prettier solution for this is to add JsonOptions in your ConfigureServices like:

services.AddMvc().AddJsonOptions(options =>
{
    options.SerializerSettings.ReferenceLoopHandling = 
                               Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
Tanato
  • 895
  • 12
  • 23
2

The question is from some time ago but it still can help other people.

Try this in your 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;
});
Jimmy Hannon
  • 729
  • 5
  • 14
  • 3
    Alternative form for core: `services.AddMvcCore() .AddJsonFormatters(j => j.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore)` – CrazyPyro Jul 19 '16 at 19:38
2

This worked for me with .NET Core 3.0.

services.AddMvcCore().AddNewtonsoftJson(
    options => options.SerializerSettings.ReferenceLoopHandling =
        Newtonsoft.Json.ReferenceLoopHandling.Ignore);
Dustin C
  • 215
  • 6
  • 15