首页 > 解决方案 > 在 WebAPI 中使用 SignalR Core 将消息推送到客户端。(使用 .Net Core 3.1)

问题描述

我尝试在 .NetCore 3.1 WEBApi 中使用 SignalR 将通知/消息推送到连接的客户端。我花了几个小时阅读有关该主题的内容,但我仍然想念一些零碎的东西来让它发挥作用。到目前为止,在我的 WebAPI 中,我有:

一个空的集线器类:

    public class PLHub : Hub
    {
    }

带有 IHubContext 注入的通知类:

using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;

namespace PadleloggAPI.Controllers
{
    public class PLNotifier
    {
        private readonly IHubContext<PLHub> mPLHubContext;

        public PLNotifier(IHubContext<PLHub> hubContext)
        {
            mPLHubContext = hubContext;
        }

        public async Task Notify(string user, string message)
        {
            await mPLHubContext.Clients.All.SendAsync("ReceiveMessage", user, message);
        }

    }
}

在我的 Startup 课程中,我有:

 app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub<PLHub>("/PLHub");
            });

在我的 ConfigureServices 中,我有:

            services.AddSignalR();
            services.AddSingleton<PLHub>();

我缺少的是在我的 api 控制器类中写什么来发送通知:

        // POST: api/Logg
        [HttpPost]
        public async Task<ActionResult<LoggInstans>> PostLoggInstans(LoggInstans loggInstans)
        {
            _context.PadleLogg.Add(loggInstans);
            await _context.SaveChangesAsync();

            // HERE I WANT TO SEND MY NOTIFICATION TO ALL CLIENTS BUT HOW???

            return CreatedAtAction("GetLoggInstans", new { id = loggInstans.Id }, loggInstans);
        }

我不确定我是否完全理解了这个概念,所以我的代码中很可能还有其他错误。

标签: asp.net-core-webapiasp.net-core-signalr.net-core-3.1signalrcore

解决方案


推荐阅读