asp.net-mvc - SignalR Asp.net core Web 应用程序中消息未从服务器发送到客户端

标签 asp.net-mvc asp.net-core-mvc signalr signalr.client

当我从服务器向客户端发送消息时客户端不显示消息

这是我注册 Hub 的 Program.cs 文件

using SignalR.Hubs;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSignalR();

builder.Services.AddControllersWithViews();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
  app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapHub<NotificationHub>("/notificationHub");

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

这是我的服务器 Controller

  public class ServerController : Controller
    {
        [HttpGet]
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Index(Notification modal)
        {
            return View();
        }
    }

这是JS文件

"use strict";

var connection = new signalR.HubConnectionBuilder()
    .withUrl("/notificationHub")
    .build();
connection.start();
console.log(connection);
connection.on("ReceiveMsg", function (msg) {
    alert('message')
    console.log('message ',msg)
    var li = document.createElement("li");
    li.textContent = msg;
    document.getElementById("msgList").appendChild(li);
})

这是我的客户端 Html

<h1>Client App</h1>

<div id="servermsg">
    <ul id="msgList">
   

    </ul>
</div>
<script src="~/lib/signalr/dist/browser/signalr.js"></script>
<script src="~/js/ClientNotification.js"></script>

这是我的中心文件。

当我调试 Hub 文件时,发送消息时不重定向

public class NotificationHub:Hub
    {
        public async Task SendMessage(string message)
        {
            await Clients.All.SendAsync("ReceiveMsg", message);
        }
    }

我更新并添加了有问题的 Program.cs 文件

最佳答案

由于您使用的是 SignalR 客户端 (JavaScript),您也可以轻松地从客户端发送消息。 工作流程是这样的:

JavaScript 客户端

  1. 设置中心并将其映射到 Program.cs 中(您已正确完成)
  2. 添加要在中心监听的事件(在您的情况下,您使用 SendMessage 方法在 NotificationHub 中正确完成了该操作)
  3. 添加 SignalR 客户端库并连接到集线器
  4. 在 View 中创建表单,并在单击“提交”时附加事件监听器(使用 JavaScript)
  5. 如果已验证上一步,并且您确定可以安全地发送消息,调用 signalR.HubConnectionBuilder 中的 invoke 方法

以下是我在上一个列表中的意思的一个工作示例: JavaScript(客户端):

"use strict";

//This is your code which is working fine
var connection = new signalR.HubConnectionBuilder()
    .withUrl("/notificationHub")
    .build();

connection.start();
console.log(connection);

connection.on("ReceiveMsg", function (msg) {
    alert('message')
    console.log('message ', msg);
    var li = document.createElement("li");
    li.textContent = msg;
    document.getElementById("msgList").appendChild(li);
});

//New code

//Event listener attached to the submit button
document.querySelector("#form-submit-btn").addEventListener("click", () => {

    //This needs to be called if the message is validated
    //You can run this conditionally based on the logic you wanna implement
    connection.invoke("SendMessage", document.querySelector("#message-input").value);
});

查看

<h1>Client App</h1>

<div id="servermsg">
    <ul id="msgList">
   

    </ul>
</div>

<input type="text" id="message-input" />

<button id="form-submit-btn" class="btn btn-primary">Send</button>

.NET 客户端

这是针对 JavaScript 客户端所说的。 .NET 客户端的过程相同

  1. 从 Nuget 包管理器安装 Microsoft.AspNetCore.SignalR.Client
  2. 配置类型为HubConnection的依赖注入(inject)
  3. 构造函数中启动连接
  4. 在操作中调用 InvokeAsync 方法

这里是 Controller 的示例代码:

private readonly HubConnection _hubConnection;

public HomeController(ILogger<HomeController> logger)
{
    _logger = logger;
    _hubConnection = new HubConnectionBuilder()
        .WithUrl("https://localhost:7159/notificationHub")
        .Build();

    _hubConnection.StartAsync();
}

[HttpPost]
public async Task MessageHandler(string message)
{
    await _hubConnection.InvokeAsync<string>("SendMessage", message);
}

查看

<div id="servermsg">
    <ul id="msgList">
   

    </ul>
</div>

<form asp-action="MessageHandler">
    <input type="text" name="message" id="message-input" />

    <button id="form-submit-btn" class="btn btn-primary">Send</button>
</form>

invoke 方法 (JS) 的 Microsoft 文档:Call hub methods from JavaScript client

invoke 方法的 Microsoft 文档 (.NET C#):Call hub methods from .NET client

关于asp.net-mvc - SignalR Asp.net core Web 应用程序中消息未从服务器发送到客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73163987/

相关文章:

asp.net-mvc - URL 重写和 IIS Express : some rules work, 有些没有

c# - 在 Web 应用程序中通过 Azure Active Directory 进行身份验证

c# - 使用 SignalR 时跟踪用户操作

websocket - JMeter 中的 Signalr 负载测试

asp.net-mvc - 如何编写 C# 扩展方法将域模型对象转换为接口(interface)对象?

c# - 如何获取经过身份验证的用户名、IP 地址和从 HTTP 过滤器调用的 Controller 操作?

asp.net-mvc - 使用 Javascript 访问 ASP.NET MVC 模型数据

c# - 在跨 Controller 的 c# MVC 中使用数据保护加密解密

c# - 库 ApiController 自定义路由

c# - SignalR 设置不正确?