.net Core 中signalR的实现

下载nuget包,按照readme在Startup.cs中ConfigureServices方法中增加services.AddSignalR();
Configure增加app.UseSignalR(u => u.MapHub("/chathub"));
npm install @aspnet/signalr 通过npm把signalr.js下到本地,然后添加到项目中。
然后创建hub类(集线器类)

public class Chat : Hub
    {
        /// 
        /// 向所有人推送消息
        /// 
        /// 
        /// 
        /// 
        public async Task SendMessage(string user, string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", Context.ConnectionId, message);
        }
    }

创建index页面,用以下内容覆盖

@page
 
 
User..........
Message...

 
    @* If you need a version of the chat script that is compatible with IE 11, replace the above *@

    上面是客户端如何调用signalR的服务器端,同时也会存在controller需要访问服务器端,这么实现

    	[Route("api")]
        [ApiController]
        public class ApiController : ControllerBase
        {
            private readonly IHubContext _hubContext;
            public ApiController(IHubContext hubContext)
            {
                _hubContext = hubContext;
            }
    
            [HttpPost,Route("send")]
            public string Create([FromBody] string value)
            {
    
                if (value == "gift")
                {
                    _hubContext.Clients.All.SendCoreAsync("ReceiveMessage", new object[] { "giftCoupon", "Start" });
                    Thread.Sleep(20000);
                    return value;
                }
                else if (value == "end")
                {
                    _hubContext.Clients.All.SendCoreAsync("ReceiveMessage", new object[] { "giftCoupon","Over"});
                }
                return "error";
            }
        }
    

    你可能感兴趣的:(.net Core 中signalR的实现)