0

I have a .NET class that I am passing from web server to browser client via standard SignalR (C#, ASP.NET, Visual Studio 2013 Community).

This class contains a property that is itself a reference to the same class (i.e. a foreign key reference in database terminology).

public class Server
{
    public Guid ServerId;
    public GridLocation Location;
    public DateTime DeployedTs;
    public Server ParentServer;
}
public class GridLocation
{
    public Guid GridLocationId;
    public int X;
    public int Y;
    public Server ServerAtLocation;
}

When my code sends only simple types (int, String as so on) all is ok. As soon as I put in a class with a property that itself refers to my Server class and try to send this to the browser client, I get the error message: "Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property 'ServerAtLocation' ..."

The code attempting to call the SignalR hub to pass data to connected clients is:

IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<WHub>();
hubContext.Clients.All.serverStatusChangedToClient(myServer);

Where WHub is my Hub which again works fine without these complex classes.

Since this is a SignalR application I am not sure I have any control over the serialization into JSON, or do I? How do I send an instance of this object including the JSON representation of the GridLocation and ParentServer objects (but no further depth in the hierarchy of objects than that)?

FalconRime
  • 13
  • 6
  • 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:40

2 Answers2

3

Look at Replacing IJsonSerializer serializer here https://github.com/SignalR/SignalR/wiki/Extensibility, the setting you need is called ReferenceLoopHandling http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_ReferenceLoopHandling.htm

Though I would strongly advise against passing complex object graphs between application boundaries.

ovolko
  • 2,777
  • 2
  • 21
  • 26
1

In Microsoft.AspNetCore.Signalr(1.1.0) in the startup.cs in ConfigureServices method You can do the following

services.AddSignalR().AddJsonProtocol(o =>
            {
                o.PayloadSerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            });