我对asp.net-core上的signalr2不太熟悉,正在尝试创建一个POC,以了解如何使用signalr2与管理员和客户端一起实现实时CRUD应用程序,但是遇到signalr数据问题推,我在此行NullReferenceException: Object reference not set to an instance of an object.
上不断收到await Clients.All.SendAsync("BroadcastData", data);
以下是我使用一些在线示例来设置集线器的方法:
public class OddPublisher : Hub
{
private readonly IOddServices _oddService;
public OddPublisher(IOddServices oddService)
{
_oddService = oddService;
}
public async Task BroadcastData()
{
var data = _oddService.ClientQueryOdds();
await Clients.All.SendAsync("BroadcastData", data); //breaks here
}
}
这是由管理员触发的,在成功提交和保存数据后,我称BroadcastData()
public class BaseController : Controller
{
public IOddServices _oddService;
public readonly OddPublisher _publisher;
public BaseController(IOddServices oddService, )
{
_oddService = oddService;
_teamService = teamService;
_publisher = new OddPublisher(oddService);
}
[HttpPost]
public async Task<IActionResult> odd_entry(CreateOdd dto)
{
//somecode here...
var results = _validator.Validate(dto);
if(!results.IsValid)
{
results.AddToModelState(ModelState, null);
return View(dto);
}
_oddService.CreateOddAndTeam(dto);
await _publisher.BroadcastData(); //Breaks
return RedirectToAction(nameof(index));
}
}
按照Microsoft Asp.Net Core Signalr文档中的建议完成所有指示,我的启动已添加了所有必需的服务。
这是客户端和JS文件,
"use strict";
var connection = new signalR.HubConnectionBuilder().withUrl("/oddPublisher").build();
connection.on("BroadcastData", data => {
console.table(data);
//getAll();
})
connection.start().then(function () {
getAll();
}).catch(function (err) {
return console.error(err.toString());
});
function getAll() {
var model = $('#dataModel');
$.ajax({
url: '/home/GetLatestOddData',
contentType: 'application/html ; charset:utf-8',
type: 'GET',
dataType: 'html',
success: function (result) { model.empty().append(result); }
});
}
这里需要一些帮助,我仍然不知道出了什么问题,如果能在此方面获得任何帮助,我将不胜感激。
谢谢。
答案 0 :(得分:0)
事实证明,我需要将IHubContext注入到集线器中才能访问客户端。