Signalr Return 模型对象

Signalr Return Model Object

故事是,我有 ROOM 模型 class。我想 return json 使用 Signalr。可能吗 ?如果是,我该如何使用它?

PS:而且我知道我不会 return 向客户提供房间对象。

public List<RoomModel> GetRooms()
        {
            GameUser user = _gameService.GetUserByClientId(Context.ConnectionId);

        var room = _gameService.GetAllowedRooms(user).Select(r => new RoomModel
        {
            Name = r.Name,
            Count = 0,
            Private = r.Private,
            Closed = r.Closed,
        }).ToList();

        return room;
    }

当您将对象发送给客户端时,SignalR 会自动序列化您的对象。 (我假设你的客户是 javascript。)

如您在 this example 中所见,他们正在发送 ShapeModel 复杂对象以在 javascript 中处理。序列化全部自动化。

如果您的示例中的方法是集线器方法,我建议您以不同的方式结束它。您可能不会返回值,而是调用客户端事件。所以:

public class RoomHub : Hub {
    public void GetRooms() {
        List<Room> rooms = new List<Room>();
        rooms.Add( new Room{ Name = "Room1", Count = 12, Closed = true, Private = false});
        rooms.Add( new Room{ Name = "Room2", Count = 20, Closed = false, Private = true});

        // sending a list of room objects
        Clients.Client(Context.ConnectionId).roomInfo(rooms);
    }
}

// Room class (your complex object)
public class Room
{
    public string Name { get; set; }
    public int Count { get; set; }
    public bool Private { get; set; }
    public bool Closed { get; set; }
}

查看有关从中心方法调用的详细信息here

然后javascript客户:

var roomHub = $.connection.roomHub;

roomHub.client.roomInfo = function (rooms) {
    // the parameter rooms is a serialized List<Room>
    // which here will be an array of room objects.
    console.log(rooms);
    // You can read the room properties as well
    for (i=0; i<rooms.length; ++i) {
        console.log(rooms[i].Name);
        console.log(rooms[i].Count);
    }  
}

$.connection.hub.start().done(function () {
    console.log("You are connected");
    roomHub.server.getRooms();
});

在我的浏览器控制台上: