asp.net core SignalR
创建一个空web
1.添加依赖
public void ConfigureServices(IServiceCollection services) { services.AddSignalR(); }
2.路由设置
app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapHub<ChatHub>("/chathub"); });
3.创建Hub
客户端调用后返回给客户端
public class ChatHub : Hub { public Task SendMessage(string user, string message) { //使用将消息发送到所有连接的客户端 return Clients.All.SendAsync("ReceiveMessage", user, message); //使用将消息发回给调用方 //return Clients.Caller.SendAsync("ReceiveMessage", message); //向组中的所有客户端发送一条消息 //return Clients.Group("SignalR Users").SendAsync("ReceiveMessage", message); } }