After following a tutorial on the Microsoft site for creating a SignalR app, I attempted to use a local API to update a counter in real-time using AJAX.
function getALL() {
$.ajax({
url: 'http://localhost:8080/api/GetCount',
contentType: 'application/json ; charset:utf-8',
type: 'GET',
success: function (data) {
console.log(data);
document.getElementById("messageList").innerHTML = data[0].Count;
}
});
}
I then initialized the hub with:
var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
connection.on("ReceiveMessage", function () {
getALL();
});
connection.start().then(function () {
getALL();
connection.invoke("SendMessage").catch(function (err) {
return console.error(err.toString());
});
}).catch(function (err) {
return console.error(err.toString());
});
Although this code initially worked and displayed the data, it did not update when a new row was added. I wondered if my implementation of AJAX was incorrect or if my hub needed an Entity Model.
Below is a snippet from my Hub:
public class ChatHub : Hub
{
private IHubContext<ChatHub> _hubContext;
public ChatHub(IHubContext<ChatHub> hubContext) { _hubContext = hubContext; }
public async Task SendMessage()
{
await _hubContext.Clients.All.SendAsync("ReceiveMessage");
}
}
}
I also included the hub in my Startup.cs file as recommended:
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ChatHub>("/chatHub");
endpoints.MapFallbackToPage("/_Host");
});
I am working with net Core 3.1 and any guidance would be appreciated. This seemingly simple modification has been challenging thus far. Thank you for your help.