send a list of different objects with the same base via SignalR to the clients
You can try to achieve the requirement by creating and using a custom converter, like below.
In custom converter MyConverterWithTypeDiscriminator
public override void Write(Utf8JsonWriter writer, Update value, JsonSerializerOptions options)
{
writer.WriteStartObject();
if (value is UpdateA updateA)
{
writer.WriteNumber("TypeDiscriminator", (int)TypeDiscriminator.UpdateA);
writer.WriteString("PropertyA", updateA.PropertyA);
}
else if (value is UpdateB updateB)
{
writer.WriteNumber("TypeDiscriminator", (int)TypeDiscriminator.UpdateB);
writer.WriteString("PropertyB", updateB.PropertyB);
}
writer.WriteString("UpdatedAt", value.UpdatedAt);
writer.WriteEndObject();
}
Base class and derived classes
public class Update
{
public DateTime UpdatedAt { get; set; }
}
public class UpdateA : Update
{
public string PropertyA { get; set; }
}
public class UpdateB : Update
{
public string PropertyB { get; set; }
}
In Startup.cs
services.AddSignalR().AddJsonProtocol(options => options.PayloadSerializerOptions.Converters.Add(new MyConverterWithTypeDiscriminator()));
In Hub method
var updates = new List<Update>
{
new UpdateA
{
UpdatedAt=DateTime.Now.AddDays(-1),
PropertyA = "A"
},
new UpdateB
{
UpdatedAt=DateTime.Now.AddDays(-1),
PropertyB = "B"
}
};
await Clients.All.SendAsync("ReceiveUpdate", updates);
Test Result

Note: to implement your custom converter, please check this link: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-converters-how-to#support-polymorphic-deserialization