要在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,并实现实时通信功能。