要在ASP.NET Core中集成SignalR,需要執行以下步驟:
dotnet add package Microsoft.AspNetCore.SignalR
services.AddSignalR();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ChatHub>("/chatHub");
});
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
connection.on("ReceiveMessage", function (user, message) {
console.log(user + " says: " + message);
});
connection.start().then(function () {
connection.invoke("SendMessage", "Alice", "Hello!");
}).catch(function (err) {
return console.error(err.toString());
});
通過以上步驟,就可以成功在ASP.NET Core應用程序中集成SignalR,并實現實時通信功能。