我在SignalR中有一个事件没有到达,而其他人确实到达了。
发送代码:
IHubContext<IServerHubProxy> _hubContext=...
MyClass message1 = new MyClass ();
MyClass message2 = new MyClass () { new MyMessage(Guid.NewGuid(), 0, 1), new MyMessage(Guid.NewGuid(), 1, 1) };
await _hubContext.Clients.All.SendMessage(message1);
await _hubContext.Clients.All.SendMessage(message2);
await _hubContext.Clients.All.SendSimpleMessage("Hello");
接收代码:
IClientHubProxy _hubTypedProxy=...
_hubTypedProxy.SendMessage(args => {
Console.WriteLine("Messages received: {0} {1}", args.Messages.Count, string.Join(",", args.Messages));
});
_hubTypedProxy.SendSimpleMessage(args => {
Console.WriteLine("Message received: {0}", args));
});
IServerHubProxy
public interface IServerHubProxy
{
Task SendMessage(MyClass message);
Task SendSimpleMessage(string message);
}
IClientHubProxy
public interface IClientHubProxy: IClientHubProxyBase
{
IDisposable SendMessage(Action<MyClass> messageHandler);
IDisposable SendSimpleMessage(Action<string> messageHandler);
}
MyClass的
[DataContract]
public class MyClass
{
[DataMember]
public List<MyMessage> Messages { get; set; }
public MyClass()
{
Messages = new List<MyMessage>();
}
}
MyMessage
[DataContract]
public class MyMessage : MyMessageBase
{
[DataMember]
public Guid MessageID { get; set; }
public MyMessage(Guid messageId, int messageType, int enabled)
: base(messageType, enabled)
{
MessageID = messageId;
}
}
MyMessageBase
[DataContract]
public class MyMessageBase
{
[DataMember]
public int MessageType { get; set; }
[DataMember]
public int Enabled { get; set; }
public MyMessageBase(int messageType, int enabled)
{
MessageType = messageType;
Enabled = enabled;
}
}
控制台结果:
收到的消息:0
收到的消息:您好
预期结果:
收到的消息:0
收到的消息:2 MyMessage,MyMessage
收到的消息:您好
答案 0 :(得分:4)
经过几个小时的调试后我发现:
所以
我模拟了SignalR完成的反序列化过程,以及我从Received
事件得到的消息,我终于得到了
因此,针对此特定问题的解决方案是在要通过SignalR传输的消息中为要使用的任何对象添加无参数构造函数:
<强> MyMessage 强>
[DataContract]
public class MyMessage : MyMessageBase
{
[DataMember]
public Guid MessageID { get; set; }
public MyMessage(Guid messageId, int messageType, int enabled)
: base(messageType, enabled)
{
MessageID = messageId;
}
public MyMessage() { }
}
<强> MyMessageBase 强>
[DataContract]
public class MyMessageBase
{
[DataMember]
public int MessageType { get; set; }
[DataMember]
public int Enabled { get; set; }
public MyMessageBase(int messageType, int enabled)
{
MessageType = messageType;
Enabled = enabled;
}
public MyMessageBase() { }
}