SignalR:无法访问默认的集线器方法
SignalR : Cannot access default hub methods
在我的 Angular 项目中,在我的项目中使用 TypedHub 接口(称为 IDemoHubTypedClient),如下所示:
IDemoHubTypedClient:
public interface IDemoHubTypedClient
{
Task BroadcastData(object data);
Task SendMessageToClient(string title, string name, string message);
}
但是,由于我继承自 Hub<IDemoHubTypedClient>
而不是 Hub
,因此我无法访问默认的集线器方法,即如下所示的 SendAsync()
,只能访问 IDemoHubTypedClient
即 BroadcastData()
和 SendMessageToClient()
。由于我需要使用这个结构来使用 DI 和 TypedHub,我该如何解决这个问题?我是否应该在 IDemoHubTypedClient
中添加所有集线器方法(SendAsync()
等)?如您所知,这些方法只有密封,因为它们在客户端(我调用 BroadcastData()
方法,这个方法实际上在客户端)。有什么想法吗?
演示中心:
public class DemoHub : Hub<IDemoHubTypedClient>
{
public async Task SendMessageToAll(string user, string message)
{
await Clients.All.SendAsync(user, message);
}
}
没那么容易。您需要准备好 SignalR ConnectionManager(依赖注入),并从那里获取类型化的 HubContext,然后您可以访问给定的 Hub 的功能。
在此处查看更多信息:https://codeopinion.com/practical-asp-net-core-hubcontext/
我认为如果您想使用强类型集线器,您必须在接口上定义所有客户端方法。据我所知,在强类型集线器和普通集线器之间无法 "mix-and-match" 。如果您有这样的客户:
this.connection.on('receiveMessage', (message: string) => {
// Do things
});
this.connection.on('receiveData', (data: MyData, message: string) => {
// Do things
});
那么如果你想使用强类型集线器,你必须使用相同名称和签名的方法定义强类型集线器接口(方法名称不区分大小写):
public interface IDemoClient
{
Task ReceiveMessage(string message);
Task ReceiveData(MyData data, string message);
}
好处是可以写await Clients.All.ReceiveMessage("Hello from server!")
而不是await Clients.All.SendAsync("ReceiveMessage", "Hello from server!")
。重点是您不必对客户端方法名称进行硬编码,并且可以对方法参数进行额外的静态类型检查。
在我的 Angular 项目中,在我的项目中使用 TypedHub 接口(称为 IDemoHubTypedClient),如下所示:
IDemoHubTypedClient:
public interface IDemoHubTypedClient
{
Task BroadcastData(object data);
Task SendMessageToClient(string title, string name, string message);
}
但是,由于我继承自 Hub<IDemoHubTypedClient>
而不是 Hub
,因此我无法访问默认的集线器方法,即如下所示的 SendAsync()
,只能访问 IDemoHubTypedClient
即 BroadcastData()
和 SendMessageToClient()
。由于我需要使用这个结构来使用 DI 和 TypedHub,我该如何解决这个问题?我是否应该在 IDemoHubTypedClient
中添加所有集线器方法(SendAsync()
等)?如您所知,这些方法只有密封,因为它们在客户端(我调用 BroadcastData()
方法,这个方法实际上在客户端)。有什么想法吗?
演示中心:
public class DemoHub : Hub<IDemoHubTypedClient>
{
public async Task SendMessageToAll(string user, string message)
{
await Clients.All.SendAsync(user, message);
}
}
没那么容易。您需要准备好 SignalR ConnectionManager(依赖注入),并从那里获取类型化的 HubContext,然后您可以访问给定的 Hub 的功能。 在此处查看更多信息:https://codeopinion.com/practical-asp-net-core-hubcontext/
我认为如果您想使用强类型集线器,您必须在接口上定义所有客户端方法。据我所知,在强类型集线器和普通集线器之间无法 "mix-and-match" 。如果您有这样的客户:
this.connection.on('receiveMessage', (message: string) => {
// Do things
});
this.connection.on('receiveData', (data: MyData, message: string) => {
// Do things
});
那么如果你想使用强类型集线器,你必须使用相同名称和签名的方法定义强类型集线器接口(方法名称不区分大小写):
public interface IDemoClient
{
Task ReceiveMessage(string message);
Task ReceiveData(MyData data, string message);
}
好处是可以写await Clients.All.ReceiveMessage("Hello from server!")
而不是await Clients.All.SendAsync("ReceiveMessage", "Hello from server!")
。重点是您不必对客户端方法名称进行硬编码,并且可以对方法参数进行额外的静态类型检查。