在SignalR中序列化/反序列化派生对象 [英] Serializing/deserializing derived objects in SignalR

查看:253
本文介绍了在SignalR中序列化/反序列化派生对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将SignalR 1.1与.NET客户端一起使用. 我的集线器中有一个方法可以接受BaseMessage类的对象并将其广播给所有客户端:

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);

我指定了TypeNameHandling.在应用程序启动时所有的序列化程序设置:

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.

推荐答案

SignalR不支持此方案,因为它将要求您的JSON有效负载包含有关派生类型和程序集的信息.请参阅此样本. 在有效负载中添加类型信息在浏览器中无法很好地发挥作用.我建议您创建单独的中心方法来处理每种派生类型.

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.

这篇关于在SignalR中序列化/反序列化派生对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆