信号器无法从控制器工作,我假设它找不到客户端



我正在尝试从控制器广播消息。基本上,我要做的就是在保存特定对象时向每个人的仪表板发送通知。在我的JS中,我有连接方法,我可以向服务器发送消息并从中获取消息,所以我知道我连接到集线器,但是在我的控制器中使用GlobalHost.ConnectionManager.GetHubContext<MyHub>()方法来获取上下文,它似乎没有发送到任何客户端。

中心
public class UpdateHub : Hub
{
    public void Update()
    { 
        Clients.All.update("You've reached the hub");
    }
}

控制器(在我的模型保存之后,但在返回视图之前,模型保存并运行)

var updateHubContext = GlobalHost.ConnectionManager.GetHubContext<UpdateHub>();
updateHubContext.Clients.All.update("A new model has been saved");

关于更新方法的调试显示…

updateHubContext.Clients.All.update("A new model has been saved");
Id = 1714, Status = RanToCompletion, Method = "{null}", Result = ""
AsyncState: null
CancellationPending: false
CreationOptions: None
Exception: null
Id: 1714
Result: null
Status: RanToCompletion

但是,如果它运行到完成,为什么客户端没有看到它?如果我将更新方法发送到服务器,客户机就会看到它。

var myhub = $.connection.notificationHub;
myhub.server.Update();
myhub.client.update = function(message) {
    alert(message);
}
$.connection.hub.start();

你知道我哪里错了吗?

我也在使用Autofac,我不认为问题在那里,但这里是它的代码。

var config = new HubConfiguration();
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterHubs(Assembly.GetExecutingAssembly()).SingleInstance();
var container = builder.Build();
config.Resolver = new Autofac.Integration.SignalR.AutofacDependencyResolver(container);
DependencyResolver.SetResolver(new Autofac.Integration.Mvc.AutofacDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver((IContainer)container);
app.UseAutofacMiddleware(container);
app.UseAutofacMvc();
app.MapSignalR("/signalr", config);
ConfigureAuth(app);

您可以尝试这样做:

var myhub = $.connection.notificationHub;
myhub.client.update = function(message) {
    alert(message);
}
$.connection.hub.start().done(function(){
    myhub.server.update();    
});

您需要在开始连接之前注册一个客户端回调方法。以下内容来自ASP。. NET SignalR Hubs API指南- JavaScript客户端-如何建立连接

注意:通常在调用start方法建立连接之前注册事件处理程序。如果您想在建立连接之后注册一些事件处理程序,您可以这样做,但是您必须在调用start方法. ...

之前注册至少一个事件处理程序。

我也认为你在开始连接之前试图在服务器上调用一个方法。

我需要为Autofac注入一个生命周期作用域。

private readonly ILifetimeScope _hubLifetimeScope;
public UpdateHub(ILifetimeScope lifetimeScope)
{
    _hubLifetimeScope = lifetimeScope.BeginLifetimeScope("AutofacWebRequest");
}

在文档里。此外,我需要在Autofac中单独注册集线器,并将其注册为ExternallyOwned

最新更新