Connecting to SignalR from Chrome extension - error: method could not be resolved

Connecting to SignalR from Chrome extension - error: method could not be resolved

我正在构建一个 Chrome 扩展,它将与 SignalR HUB 交互。

HUB 可以正常处理我使用代理连接创建的本地文件。但是,我无法在 chrome 扩展中使用代理连接,因为它不在同一个项目中,所以我必须自己定义它:

var connection = $.hubConnection('http://localhost:61xxx/signalr/hubs', {useDefaultPath: false});
var roomIndexHubProxy = connection.createHubProxy('roomIndexHub');

这工作正常,如果我在服务器 OnConnected 方法上使用断点,它会触发,而且我还看到表明连接已建立的日志。但是当我尝试 运行 我自己的函数时,我得到这个错误(在客户端):

SignalR: 'test' method could not be resolved. No method found with that name. at Microsoft.AspNet.SignalR.Hubs.NullMethodDescriptor.b__0(IHub emptyHub, Object[] emptyParameters) at Microsoft.AspNet.SignalR.Hubs.HubDispatcher.Incoming(IHubIncomingInvokerContext context) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult() at Microsoft.AspNet.SignalR.TaskAwaiterHelper.PreserveCultureAwaiter1.GetResult() at Microsoft.AspNet.SignalR.Hubs.HubPipelineModule.<>c__DisplayClass1.<b__0>d__3.MoveNext().

SignalR: roomindexhub.test failed to execute. Error: 'test' method could not be resolved. No method found with that name.

这是我的客户端代码:

var connection = $.hubConnection('http://localhost:61xxx/signalr/hubs', {useDefaultPath: false});
var roomIndexHubProxy = connection.createHubProxy('roomIndexHub');

connection.logging = true;
connection.start().done(function() {
    // Wire up Send button to call RoomIndexHubProxy on the server.
    console.log('Hub has started');
    $("#signalr").click(function(){
        roomIndexHubProxy.invoke('test');
    });

});

connection.error(function (error) {
    console.log('SignalR error: ' + error)
});

服务器端代码(虽然很简单):

public class RoomIndexHub : Hub
    {
        public RoomIndexHub(){}

        public override Task OnConnected()
        {
            return base.OnConnected();  // this works!
        }

        internal void test()
        {
            int i = 0;   // this doesn't work
        }
    }   
}

当我写这些行时,我在 Microsoft.AspNet.SignalR.Hubs.NullMethodDescriptor.b__0(IHub

emptyHub, Object[] emptyParameters)`.

但是我不知道为什么会这样,因为我确实定义了:

var roomIndexHubProxy = connection.createHubProxy('roomIndexHub');

非常感谢您的帮助!

internal 关键字的 documentation 表示:

Internal types or members are accessible only within files in the same assembly

换句话说,外部无法访问,所以只需删除 internal