asp.net-core-webapi - 在 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);
}
我不确定我是否完全理解了这个概念,所以我的代码中很可能还有其他错误。
解决方案
推荐阅读
- go - 用于公共和私有路由中间件的 httprouter 和 negroni
- r - 特定列的 R 中每个分组变量的gather()
- clojure - 通过顺序调用 main 函数然后在它们之间进行通信来运行两个 clojure 代码
- javascript - Sequelize - TypeError:无法读取未定义的属性“定义”
- javascript - 如何在 VUE js 中为直播网站编写自动调用功能?
- linux - Google Compute Engine 实例需要 sudo 密码 - 我的密码是什么?
- apache-spark - 如何在 AWS EMR 集群 5.27 中更新 spark 库
- c - 字体资源加载/显示位图问题
- hadoop - yarn.resourcemanager.am.max-attempts 的真正含义是什么?
- mysql - 一起寻找相似兴趣的查询