要在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,并实现实时通信功能。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: ASP.NET panel控件的用法是什么