如何在ASP.NET控制器中发送Clients值



我用c#、javascript编写了一段代码,使用客户端库SignalR刷新数据库值更改中的页面。我的代码是

<form asp-action="Start" method="post" class="form-stacked">
<button type="submit" id="startPractice" class="button-primary">Start Practice</button>
</form>
<script src="~/js/ignalr/dist/browser/signalr.js"></script>
<script src="~/js/chat.js"></script>

我的API方法是在点击开始练习时调用的

public async Task<IActionResult> Index(long sessionId)
{
// Database change logic
SignalRClientHub sr = new SignalRClientHub();
await sr.SendMessage();
// Rest of the logic
return this.View();
}
public class SignalRClientHub : Hub
{
public async Task SendMessage(string user = null, string message = null)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}

chat.js 代码

"use strict";
var connection = new signalR.HubConnectionBuilder().withUrl("/SignalRClient").build();
connection.on("ReceiveMessage", function (user, message) {
location.reload();
});

当我点击按钮开始练习时,它会点击SendMessage方法,但我得到了一个错误

object reference not set to an instance

因为客户端的值为null。我该如何解决?

不能手动新建集线器。为了从集线器外部发送到客户端,您需要使用IHubContext<THub>。有关详细信息,请参阅文档https://learn.microsoft.com/aspnet/core/signalr/hubcontext?view=aspnetcore-5.0

最新更新