Search code examples
angulardictionaryasp.net-coresignalrdisconnect

SignalR angular gets disconnected while getting a dictionary object


Using asp.net core 2.2 and angular 7, (asp.netcore:signalr 1.1.0 + angular:"@aspnet/signalr": "^1.1.4")

it was working fine until i tried to send a dictionary to angular. when it tries to send the dictionary it gets disconnected.

Utils.js:209 [2019-12-29T11:09:11.959Z] Information: WebSocket connected to ws://localhost:64408/chat?id=6d-C7eu1X-Pv8t4-RwdbYg. 
Utils.js:209 [2019-12-29T11:09:12.132Z] Information: Connection disconnected.

These are my codes:

InMemoryChatRoomService class:

 public class InMemoryChatRoomService : IChatRoomService
    {
        private readonly Dictionary<Guid, ChatRoom> _roomInfo = new Dictionary<Guid, ChatRoom>();

        public Task<IReadOnlyDictionary<Guid, ChatRoom>> GetAllRooms()
        { 
            return Task.FromResult(_roomInfo as IReadOnlyDictionary<Guid, ChatRoom>);
        } 

    }

IChatroomService:

using SignalR.Models;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace SignalR
{
    public interface IChatRoomService
    {

        Task<IReadOnlyDictionary<Guid, ChatRoom>> GetAllRooms(); 
    }
}

ChatHub class:

using Microsoft.AspNetCore.SignalR;
using SignalR.Models;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace SignalR
{
    public class ChatHub : Hub
    {
        private readonly IChatRoomService _chatRoomService;
        public ChatHub(IChatRoomService ChatRoomService)
        {
            _chatRoomService = ChatRoomService;

        }
        public override async Task OnConnectedAsync()
        { 
            await Clients.Caller.SendAsync("ActiveRooms", await _chatRoomService.GetAllRooms()); 
            await base.OnConnectedAsync();
        }
    }
}

angular:

import { Component, OnInit } from '@angular/core';
import * as signalR from "@aspnet/signalr";
import { HttpClient } from "@angular/common/http";
import { MessagePacket } from './MessagePacket.model';
import { ChatService } from './chat.service';
import { ChatRoom } from './ChatRoom.model';

@Component({
    selector: 'app-chat',
    templateUrl: './chat.component.html',
    styleUrls: ['./chat.component.scss']
})
export class ChatComponent implements OnInit {

    constructor(private http: HttpClient, private chatService: ChatService) { }

    private hub: signalR.HubConnection;
    rooms = [ ];
    messagePackets: MessagePacket[] = [];
    isConnected = false;
    connectionAttempts = 0;
    ipAddress = '';
    typedMessage = '';
    userChatName = 'salar';//todo: load user data

    ngOnInit() { 
        //build connection
        this.hub = new signalR.HubConnectionBuilder()
            .withUrl('http://localhost:64408/chat')
            .build();

        //start connection
        this.startConnection();


        this.hub.on('ActiveRooms', (rooms ) => {
            this.ActiveRooms(rooms)
        });


        //on disconnect
        this.hub.onclose(h => {
            this.isConnected = false;
             setTimeout(x => this.startConnection(), 3000)
        });
    }

    startConnection() {
        this.connectionAttempts++;
        console.log('Connecting!')
        this.hub
            .start()
            .then(() => {
                this.connectionAttempts = 0;
                this.isConnected = true;
                console.log('Connection started!');
                console.log('Getting all rooms');
               // this.hub.invoke("ActiveRooms");

            })
            .catch(err => {
                if (this.connectionAttempts < 10) {
                    console.log(this.connectionAttempts + ' try for connection')
                     setTimeout(x => this.startConnection(), 3000)
                } else {
                    console.log('Error while establishing connection. changed mode to manual')
                }
            });
    }


    ActiveRooms(rooms ) {
        var x = '';
       // this.rooms = rooms;
    }


}

when i trace, it tries to send back the dictionary, and after that , signalr gets disconnected and tries to connect again. if it not be dictionary and be like a string or another object, it is working fine.

UPDATE:

when i change the type GUID of dictionary to STRING it gets alright:

 public Task<IReadOnlyDictionary<string, ChatRoom>> GetAllRooms()
        {
            //type guid gives error so needs to be converted to string
            Dictionary<string, ChatRoom> result = new Dictionary<string, ChatRoom>();
            foreach (var room in _roomInfo)
            {
                result.Add(room.Key.ToString(), room.Value);
            }
            return Task.FromResult(result as IReadOnlyDictionary<string, ChatRoom>);
        } 

It has some problem with GUID.


Solution

  • SignalR has problems when it wants to serialize/deserialize a GUID and it must work on both the C# side and the JS side. GUID is a little bit tricky. It is a struct, not a class. It has a binary representation as well as a string representation.

    I found this issue: https://github.com/aspnet/SignalR/issues/1043

    From the issue description it seems, that this is a limitation of the library and there are no plans to fix it. It is actually a limitation of JavaScript itself. It does not have a built-in GUID type. The library does not give any warnings about this case.

    As a workaround you can you a string like in the example you posted or create your own type for GUID, but use only built-in primitive types of JS to define it.