0

This is my class:

public partial class Event
{
    public Event()
    {
        this.Comments = new HashSet<Comment>();
        this.Rates = new HashSet<Rate>();
        this.RawDates = new HashSet<RawDate>();
    }

    public int ID { get; set; }
    public string Title { get; set; }
    public string Summary { get; set; }
    public string SiteURL { get; set; }
    public string ContactEmail { get; set; }
    public string LogoURL { get; set; }
    public int EventType_ID { get; set; }
    public Nullable<int> Location_ID { get; set; }
    public Nullable<System.DateTime> BegginingDate { get; set; }
    public string nTrain { get; set; }
    public string Content { get; set; }

    public virtual ICollection<Comment> Comments { get; set; }
    public virtual Conference Conference { get; set; }
    public virtual ICollection<Rate> Rates { get; set; }
    public virtual ICollection<RawDate> RawDates { get; set; }
    public virtual EventType EventType { get; set; }
    public virtual Location Location { get; set; }
}

When I call web api post method, exception mentioned in the title is thrown in this line:

var response = await client.PostAsJsonAsync("api/event", event);

I added [JsonIgnore] above every virtual field in Event class. This time serialization worked, but ignored fields were not serialized, their value is null. I really need all information contained in Event object. How can I solve this problem?

Xardas
  • 1,777
  • 6
  • 20
  • 31
  • You might have a look at my answer on **[“Self Referencing Loop Detected” exception with JSON.Net](https://stackoverflow.com/questions/40472419/self-referencing-loop-detected-exception-with-json-net/51235783#51235783)** page. – Murat Yıldız Jul 08 '18 at 20:37

2 Answers2

1

Adding below configuration in WebAPIConfig.cs resolves the bug.

var json = config.Formatters.JsonFormatter;
//Below configuration to mandatory to resolve the Self referencing loop detected with       
"Newtonsoft.Json.JsonSerializationException" ,
json.SerializerSettings.PreserveReferencesHandling =    
Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
sukumarraju
  • 91
  • 1
  • 9
0

Circular referencing objects cannot be JSON serialized. I would recommend you using a view model in which you will include the properties you need and then have your action return this view model instead of the actual domain model.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928