[英]How Can I send Clients value in ASP.NET Controller?
I have written a code in c#, javascript, using client library SignalR to refresh a page in database value change.我在 c#、javascript 中编写了代码,使用客户端库 SignalR 刷新数据库值更改中的页面。 My code is
我的代码是
<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>
My API method is which is called while clicking start practice is我的 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);
}
}
code of chat.js chat.js 的代码
"use strict";
var connection = new signalR.HubConnectionBuilder().withUrl("/SignalRClient").build();
connection.on("ReceiveMessage", function (user, message) {
location.reload();
});
When I click the button start practice it hits SendMessage Method, but I got an error当我单击按钮开始练习时,它会触发 SendMessage 方法,但出现错误
object reference not set to an instance
because the value of the Client was null.因为客户端的值是 null。 How Can I fix this?
我怎样才能解决这个问题?
You cannot new up a hub manually.您不能手动新建集线器。 In order to send to clients from outside of the hub you need to use the
IHubContext<THub>
.为了从集线器外部发送给客户端,您需要使用
IHubContext<THub>
。 See the docs for details https://docs.microsoft.com/aspnet/core/signalr/hubcontext?view=aspnetcore-5.0有关详细信息,请参阅文档https://docs.microsoft.com/aspnet/core/signalr/hubcontext?view=aspnetcore-5.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.