问题
I'm needing to pass strings from my controller to a signalR hub and have it render on my page. I've followed along with the chat tutorial found at: https://docs.microsoft.com/en-us/aspnet/core/tutorials/signalr?view=aspnetcore-2.2&tabs=visual-studio
The next step from the chat tutorial is breaking it out message call to my controller like so:
[HttpPost]
public async Task<IActionResult> Upload(string engineType)
{
try
{
var message = "File Upload Failed";
await _errorHub.Clients.All.SendAsync("SendMessage", message);
return Ok();
}
catch (Exception ex)
{
Log.Error("File Upload failed: " + ex);
return NotFound();
}
}
I have injected my hub into my controller, which is how I'm able to access the Clients.All...
call.
My hub is only different from the tutorial in that I removed the user parameter:
public class UserErrorHub : Hub
{
public async Task SendMessage( string message)
{
await Clients.All.SendAsync("ReceiveMessage", message);
}
}
Finally, in my javascript, I have the following SignalR set up:
var connection = new signalR.HubConnectionBuilder().withUrl("myURL").build();
connection.on("ReceiveMessage", function (user, message) {
console.log("ReceiveMessage");
var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
var encodedMsg = user + " says " + msg;
var li = document.createElement("li");
li.textContent = encodedMsg;
document.getElementById("messagesList").appendChild(li);
});
When I run my project, the console output informs me that I hub is set up fine like so:
[2020-09-03T09:45:23.384Z] Information: Normalizing '/Signalr' to 'https://localhost:44336/Signalr'.
However, when I trigger my Upload method, nothing gets sent to my hub. What is it I'm doing wrong?
回答1:
await _errorHub.Clients.All.SendAsync("SendMessage", message);
"SendMessage" should be "ReceiveMessage"
回答2:
You are calling _errorHub.Clients.All.SendAsync("SendMessage", message)
in your controller instead of _errorHub.SendMessage(message)
. This means you're controller directly is invoking SendMessage
on your clients, but you're client is only listening to ReceiveMessage
.
So, you'll want to call _errorHub.SendMessage(message)
in your controller, which in turn calls Clients.All.SendAsync("ReceiveMessage", message)
which will trigger your clients ReceiveMessage
method
来源:https://stackoverflow.com/questions/63721149/signalr-call-from-controller