Serializing/deserializing derived objects in SignalR

若如初见. 提交于 2020-03-22 23:09:45

问题


I am using SignalR 1.1 with .NET clients. I have a single method in my hub that accepts an object of BaseMessage class and broadcasts it to all clients:

public void SendMessage(BaseMessage message)
{
    Clients.All.BroadCastMessage(message);
}

Clients will pass derived messages into this method:

_hub.Invoke("SendMessage", new ErrorMessage("Some Error")).Wait();

The client has a single message handler:

_hub.On<BaseMessage>("BroadCastMessage", OnMessageReceived);

I've specified TypeNameHandling.All serializer settings at application startup:

var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All};
var serializer = new JsonNetSerializer(settings);
GlobalHost.DependencyResolver.Register(typeof(IJsonSerializer), () => serializer);

But when the client sends a derived message, the server receives a base message.

How should I configure serializer to be able to receive derived messages?

Note: I can do serialization/deserialization manually and pass strings to the server, but this causes double serialization.


回答1:


SignalR is not supporting this scenario as it would require your JSON payload to contain information about the derived type and assembly. See this sample. Adding type information in your payload would not play well with browsers. I suggest you create individual hub methods to handle each of your derived types.



来源:https://stackoverflow.com/questions/16636415/serializing-deserializing-derived-objects-in-signalr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!