0

My project is Web Api Core 5.0 and i have got problems with self reference loop EntityFrameworkCore

In my last project i have used this:

  services.AddControllers().AddNewtonsoftJson(options => 
                options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

but on my current version .Net core it's not working, i found something like this:

    services.AddMvc().AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;
    });

but I dont like it, it shows $Id and $value on response, which i dont want to see Is there another way of the way get rid of that self reference loop?

I read before: JSON.NET Error Self referencing loop detected for type

and these don't help me

KarolZirex
  • 25
  • 4
  • Using what you used in your last project: If you're using swagger -- you might look at [this](https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/master/README.md#systemtextjson-stj-vs-newtonsoft) The key is to add the `services.AddSwaggerGenNewtonsoftSupport();` line just after the `AddSwaggerGen` block. – jimnkey Nov 16 '21 at 23:54
  • https://www75.zippyshare.com/v/Op8kXqvB/file.html – KarolZirex Nov 17 '21 at 18:06
  • Still I can't - there bellow is a screenshot – KarolZirex Nov 17 '21 at 18:08

1 Answers1

1

It was only a suggestion ... because your questions is about EF -- but the contents seem to stem from NewtonSoft and possibly Swagger. So I thought it might have more to do with Swagger for your reference loopoing issue. In any case, I've found this solves that type of issue for me. (you would need Swashbuckle.AspNetCore.Newtonsoft)

First add NewtonSoft options.

   services.AddControllers()
       .AddNewtonsoftJson(opts =>
       {
           //opts.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
           //opts.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
           opts.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
       });

Then add swaggergen... and then newtonsoft support.

    services.AddSwaggerGen(c =>
    {
        ...
    });
    // NOW add 
    services.AddSwaggerGenNewtonsoftSupport();
jimnkey
  • 342
  • 1
  • 9