我正在按照为我的 asp.net 核心项目设置信号器的指南。
在遵循本指南时,我有这段代码:
void SendMessage(string message)
{
GlobalHost
.ConnectionManager
.GetHubContext<NotificationHub>().Clients.sendMessage(
message);
}
我有一个NotificationHub看起来像这样的文件:
public class NotificationHub : Hub
{
public string Activate()
{
return "Monitor Activated";
}
}
Globalhost 用于获取Hubcontext对象。问题是当我导入 signalR 时,没有任何调用GlobalHost可用。在文档中,我可以找到有关它的信息:
GlobalHost
ASP.NET Core has dependency injection (DI) built into the framework. Services can use DI to
access the HubContext. The GlobalHost object that is used in ASP.NET SignalR to get a HubContext
doesn't exist in ASP.NET Core SignalR.
好的,所以Globalhost在核心中根本不可用。
我需要执行相同的代码,但对于Microsoft.AspNetCore.SignalR;.
我现在怎样才能拿到一个Hubcontext物体?
编辑
我现在尝试按照文档中的最小示例进行操作,并创建一个小型示例项目。我的“startup.csfile has this line, in配置服务”:
services.AddSignalR();
这行在Configure:
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<NotificationHub>("/Hubs");
});
我的 Hub 文件如下所示,如文档中所示:
namespace mvcCoreSample.Hubs
{
public class NotificationHub : Hub
{
public Task SendMessage(string user, string message)
{
return Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
}
其中 Hubs 是与 startup.cs 位于同一目录中的文件夹。我有一个看起来像这样的控制器,它调用集线器:
public class msgController : Controller
{
public IActionResult Index()
{
NotificationHub hub = new NotificationHub();
hub.SendMessage("user1", "some message");
return Content("serving content");
}
}
但是当我运行它并转到控制器的 url 时,集线器会在sendmessage函数中引发错误:
Microsoft.AspNetCore.SignalR.Hub.Clients.get returned null.
我真的看不出哪里出错了,集线器一定缺少什么?也许与建立连接有关?
编辑 2
经过几次更正后,我将控制器更改为如下所示:
public IActionResult Index(IHubContext<NotificationHub> hub)
{
var clients = hub.Clients;
return Content("serving content");
}
尽管我仍然不知道如何调用我的sendmessage函数,但我想试试这个。
在调试模式下运行此站点时,我在浏览器中抛出此错误:
InvalidOperationException: Could not create an instance of type 'Microsoft.AspNetCore.SignalR.IHubContext`1[[mvcCoreSample.Hubs.NotificationHub, mvcCoreSample, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]'. Model bound complex types must not be abstract or value types and must have a parameterless constructor. Alternatively, give the 'hub' parameter a non-null default value.