2

Делаю мессенджер с использованием клиента на WPF и серверной части на SignalR. Проблема в том, что не до конца понимаю почему не срабатывает метод в классе ChatHub под названием: SendMessages, хотя JoinChatGroup срабатывает.

Ошибка: Microsoft.AspNetCore.SignalR.HubException: "Failed to invoke 'SendMessages' due to an error on the server. InvalidDataException: Error binding arguments. Make sure that the types of the provided values match the types of the hub method being invoked."

Сторона сервера:

Класс, отвечающий за хаб.

public class ChatHub : Hub
    {
        public async Task SendMessages(Message message)
        {
            await Clients.Group(message.Chat_id.ToString()).SendAsync("ReceiveMessage", message);
            Console.WriteLine("Сообщение успешно отправлено!");
        }
        public async Task JoinChatGroup(string chatId)
        {
            await Groups.AddToGroupAsync(Context.ConnectionId, chatId);
            Console.WriteLine("Успешно добавлен в группу!");
        }
    } 

Сторона клиента:

Класс, отвечающий за подключение к хабу.

    public class SignalRService
    {
        private HubConnection hub = new HubConnectionBuilder()
            .WithUrl("http://localhost:5000/Chat")
            .Build();
        public event Action<Message> MessageReceived;
        public async void StartConnection()
        {
            await hub.StartAsync();
            hub.On<Message>("ReceiveMessage", (message) => MessageReceived.Invoke(message));
        }
        public async Task addToGroup(string chatId)
        {
            await hub.InvokeAsync<string>("JoinChatGroup", chatId);
        }
        public async Task SendMessage(Message message)
        {
            await hub.InvokeAsync<Message>("SendMessages", message);
        }
    }

Модель данных Message:

    public class Message
    {
        public int ID { get; set; }
        public int User_id { get; set; }
        public int Chat_id { get; set; }
        public int ContentType { get; set; }
        public byte[] Content { get; set; }
        public Message(int user_id, int chat_id, int contentType, byte[] content)
        {
            User_id = user_id;
            Chat_id = chat_id;
            ContentType = contentType;
            Content = content;
        }
        public Message(int iD, int user_id, int chat_id, int contentType, byte[] content)
        {
            ID = iD;
            User_id = user_id;
            Chat_id = chat_id;
            ContentType = contentType;
            Content = content;
        }

Нашел вроде дельный ответ, но не понимаю как я его должен применить к своему проекту.

https://github.com/aspnet/SignalR/issues/2937

Окно чата:

    public partial class ChatWindow : Page
    {
        private int chatID;
        private ObservableCollection<Message> messages = new ObservableCollection<Message>();
        private SignalRService rService;
        public ChatWindow(ChatUser chatUser)
        {  
            InitializeComponent();
            chatID = chatUser.chat_id;
            rService = new SignalRService();
            rService.StartConnection();
            rService.addToGroup(chatID.ToString());
            rService.MessageReceived += RService_MessageReceived;
        }

        private void RService_MessageReceived(Message obj)
        {
            MessageBox.Show("Получил сообщение!");
        }

        private async void SendMessage_Click(object sender, RoutedEventArgs e)
        {
            byte[] array = Encoding.UTF8.GetBytes(messageBox.Text);
            Message message = new Message(User.CurrentUser.ID, chatID, 1, array);
            await rService.SendMessage(message);
        }
    }

1 ответ 1

1

Решением было добавить пустой конструктор к модели Message. Так как нельзя сериализовать или десериализовать объект, у которого нет пустого конструктора.

Добавленная строка кода: public Message() { }

Новая модель Message

    public class Message
    {
        public int ID { get; set; }
        public int User_id { get; set; }
        public int Chat_id { get; set; }
        public int ContentType { get; set; }
        public byte[] Content { get; set; }
        public Message() { }
        public Message(int user_id, int chat_id, int contentType, byte[] content)
        {
            User_id = user_id;
            Chat_id = chat_id;
            ContentType = contentType;
            Content = content;
        }
        public Message(int iD, int user_id, int chat_id, int contentType, byte[] content)
        {
            ID = iD;
            User_id = user_id;
            Chat_id = chat_id;
            ContentType = contentType;
            Content = content;
        }
    }

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.