user5326354
user5326354

Reputation:

Signalr client to server push using abstract model

I've managed to set up communication using Signalr from both sides. When sending a message from server to client, I use an abstract model and have only one method at client.

I wanted to know if there was a possible way to do so similiary from the other side - from client to server, because so far I can't get this to work.

My meaning is:

Server side:

public class MyHub : Hub
{
     public void HandleNotification(BaseNotification notification)
     {
         if(notification is NewItemNotification) {
                ....
         } else if (notification is UpdatedItemNotification) {
                ....
         } else if (notification is DeletedItemNotification) {
                ....
         }
     }
}

In the following example I get an empty BaseNotification object

Upvotes: 1

Views: 244

Answers (1)

xleon
xleon

Reputation: 6365

I think this is related to how Json.Net library (internally used by SignalR) works.

When data gets to the server in Json format, SignalR will take that string and convert it to BaseNotification object. All properties defined in the Json that don´t exists in BaseNotification type will be dismissed. In other words: properties not present in BaseNotification won´t be deserialized. So your BaseNotification cannot be casted to a different type unless the property names in both types are equal.

I can think of two different solutions for your case:

a) Include all notification properties in a single object Notification, adding one more for the type (i.e: Enum NotificationType):

public void HandleNotification(Notification notification)
{
    switch (notification.Type)
    {
        case NotificationType.NewItem:
            ...
        case NotificationType.UpdatedItem:
            ...        
        case NotificationType.DeletedItem:
            ...
}

b) Create a different handle method for each notification type:

public void HandleNewNotification(NewItemNotification notification) {}
public void HandleUpdatedNotification(UpdatedItemNotification notification) {}
public void HandleDeletedNotification(DeletedItemNotification notification) {}

Upvotes: 1

Related Questions