How to send an object with a collection of generic through SignalR on Asp.Net Core

Viewed 25

On my Asp.Net core web app, I'm using SignalR to provide to my angular app some live update. One of the callback is sending data to the client

public class DataBatch
{
    public Guid DashboardId { get;set; }
    public IEnumerable<WidgetData> WidgetData { get;set; }
    public DateTime RefreshDate { get;set; }
}
public abstract class WidgetData
{
    public Guid WidgetUsageId { get; set;}
    public DateTime Timestamp { get; set;}
}

The issue is that WidgetData is abstract, and most of its implementations have additionals values. Typically:

public class ValueIndicatorData : WidgetData
{
    public IList<ValueIndicatorValue> ValueIndicatorValues { get; } = new List<ValueIndicatorValue>();
}

When I send my data to my clients:

await _hubContext.Clients.Group(dashboardId).SendDashboardData(notification.DataBatch);

My clients only receives the properties declared in WidgetData, not the one of my children classes(like the ValueIndicatorData).

How can I provide to SignalR the informations that this object has sub-classes and that their properties should be serialized?

1 Answers

I ended configuring Asp.Net Core to use NewtonSoft to serialize to JSON, while setting an option to include types, now it automatically serialize the data:

    builder.Services.AddSignalR()
        .AddNewtonsoftJsonProtocol(opts =>
        {
            opts.PayloadSerializerSettings.TypeNameHandling = TypeNameHandling.Auto;
        });

There is an alternative using the native JSON converter, but it require to build some cumbersome converters:

https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-converters-how-to?pivots=dotnet-6-0#support-polymorphic-deserialization

Related