如何在 ASP.NET 控制器中发送客户端值?
How Can I send Clients value in ASP.NET Controller?
我用 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
因为客户端的值为空。我该如何解决这个问题?
您不能手动新建集线器。为了从集线器外部发送给客户端,您需要使用 IHubContext<THub>
。有关详细信息,请参阅文档 https://docs.microsoft.com/aspnet/core/signalr/hubcontext?view=aspnetcore-5.0
我用 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
因为客户端的值为空。我该如何解决这个问题?
您不能手动新建集线器。为了从集线器外部发送给客户端,您需要使用 IHubContext<THub>
。有关详细信息,请参阅文档 https://docs.microsoft.com/aspnet/core/signalr/hubcontext?view=aspnetcore-5.0