I am able to send the message from SignalR hub from within the Hub but not from outside the hub. The following code does not work:
public class MessageSender
{
private readonly ILogger<MessageSender> _logger;
private readonly IHubContext<MessageHub> _context;
public MessageSender(ILogger<MessageSender> logger, IHubContext<MessageHub> context)
{
_logger = logger;
_context = context;
}
public async Task SendTestMessage()
{
Console.WriteLine("Sending Test Message to Client");
await _context.Clients.All.SendAsync("TestMessageReceived", new SampleData());
}
}
However the following code works:
public class MessageHub : Hub
{
public async Task InitiateConnection(SampleData data)
{
Console.WriteLine($"{data.Text});
await Clients.All.SendAsync("TestMessageReceived", new SampleData());
}
}
My client application (C#) is able to communicate to the server and call "InitiateConnection" method in hub which in return calls the "TestMessageReceived" method of the client which works fine.
Why is the MessageSender not able to send the messages ? Probably I am missing something very small. I am using .Net Core and both Server and Client are on .Net 5