Search code examples
c#asp.net-coreasp.net-core-webapiasp.net-core-signalr

SignalR client not receiving server messages


My SignalR client doesn't receive any messages from the server. What am I missing here?

Server Hub

namespace DoneITWebAPI.Hubs
{
    public interface ITypedHubClient
    {
        Task BroadcastMessage(string name, string message);
    }

    public class ServiceStatusHub : Hub<ITypedHubClient>
    {
        public void Send(string name, string message)
        {
            Clients.All.BroadcastMessage(name, message);
        }

    }
}

Controller

[Route("api/[controller]")]
[ApiController]
public class DemoController : Controller
{
    IHubContext<ServiceStatusHub, ITypedHubClient> _chatHubContext;
    public DemoController(IHubContext<ServiceStatusHub, ITypedHubClient> chatHubContext)
    {
        _chatHubContext = chatHubContext;
    }

    // GET: api/values
    [HttpGet]
    public IEnumerable<string> Get()
    {
        _chatHubContext.Clients.All.BroadcastMessage("ReceiveMessage", "test");
        return new string[] { "value1", "value2" };
    }
}

Console Client App

class Program
{
    static void Main(string[] args)
    {
        var connection = new HubConnectionBuilder()
        .WithUrl("http://localhost:64165/ServiceStatusHub")
        .Build();

        connection.On<string, string>("ReceiveMessage", (user, message) =>
        {
            GetMessage(user, message);
        });

        connection.StartAsync();

        Console.ReadKey();
    }


    public static void GetMessage(string user, string message)
    {
        //Not hitting here
    }
}

Solution

  • My SignalR client doesn't receive any messages from the server. What am I missing here?

    Based on your code, we can find that you use strongly typed hubs, and you define and name client method as ReceiveMessage on console app.

    To make you can call that client method as expected , you can try to modify your hub code as below.

    public interface ITypedHubClient
    {
        Task ReceiveMessage(string name, string message);
    }
    
    public class ServiceStatusHub : Hub<ITypedHubClient>
    {
        public void Send(string name, string message)
        {
            Clients.All.ReceiveMessage(name, message);
        }
    
    }
    

    And change the code in API action

    _chatHubContext.Clients.All.ReceiveMessage("system", "test");
    

    Test Result

    enter image description here