0
votes

I read a lot here on stackoverflow before post this, and the only that help, but not really, was

SignalR call from controller

https://docs.microsoft.com/en-us/aspnet/core/tutorials/signalr?view=aspnetcore-2.2&tabs=visual-studio

I thought that that error they say was my error, but didnt work. So When the client send a message, this should trigger the hub, but didnt... At least did show up My controller is like...

//Constructor
        private readonly IHubContext<ChatHub> chatHub;
        public UserController(IHubContext<ChatHub> hubContext)
        {
            this.chatHub = hubContext;
        }

//Method
[HttpPost]
public async Task<ActionResult> Message(Message message)
{
            await chatHub.Clients.All.SendAsync("ReceiveMessage", message.emisor, message.Text);
}

Chat.js

"use strict";

var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();

//Disable send button until connection is established
document.getElementById("sendButton").disabled = true;

connection.on("ReceiveMessage", function (user, message) {
    var msg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
    var encodedMsg = user + " says " + msg;
    var li = document.createElement("li");
    li.textContent = encodedMsg;
    document.getElementById("messagesList").appendChild(li);
});

connection.start().then(function () {
    document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
    return console.error(err.toString());
});

document.getElementById("sendButton").addEventListener("click", function (event) {
    var user = document.getElementById("userInput").value;
    var message = document.getElementById("messageInput").value;
    connection.invoke("SendMessage", user, message).catch(function (err) {
        return console.error(err.toString());
    });
    event.preventDefault();
});

ChatHub class

    public class ChatHub : Hub
    {
        public async Task SendMessage(string name, string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", name, message);
        }
    }

So, this method on chathub, did not have any reference, If I debug, didnt call this method

1

1 Answers

0
votes

You only call hub methods from the client. And you call client methods from the server.

IHubContext is on the server and all it does is send to clients. If you want to "call a hub method" from the server, then you need to refactor your code to have a common class that both the hub method calls and your controller calls.