问题描述
在我的Angular项目中,在我的项目中使用TypedHub接口(称为IDemoHubTypedClient),如下所示:
In my Angular project use TypedHub interface (called IDemoHubTypedClient) in my project as shown below:
IDemoHubTypedClient:
IDemoHubTypedClient:
public interface IDemoHubTypedClient
{
Task BroadcastData(object data);
Task SendMessageToClient(string title, string name, string message);
}
但是,由于我继承自Hub<IDemoHubTypedClient>
而不是Hub
,所以无法访问默认的集线器方法(例如SendAsync()
),如下所示,只能访问IDemoHubTypedClient
中的方法,即BroadcastData()
和.当我需要使用此结构来使用DI和TypedHub时,如何解决此问题?是否应该在IDemoHubTypedClient
中添加所有集线器方法(SendAsync()
等)?如您所知,这些方法只有在客户端使用的密封(我称BroadcastData()
方法,而该方法实际上在客户端).有什么主意吗?
However, as I inherited from Hub<IDemoHubTypedClient>
instead of Hub
, I cannot access to the default hub methods i.e. SendAsync()
as shown below and only access the methods in the IDemoHubTypedClient
i.e. BroadcastData()
and SendMessageToClient()
. As I need to use this structure for using DI and TypedHub, how can I fix this problem? Should I add all the hub methods (SendAsync()
etc.) in my IDemoHubTypedClient
? As you know there is only seals of these methods as they are on client side (I call BroadcastData()
method and this method is actually on client side). Any idea?
DemoHub:
DemoHub:
public class DemoHub : Hub<IDemoHubTypedClient>
{
public async Task SendMessageToAll(string user, string message)
{
await Clients.All.SendAsync(user, message);
}
}
推荐答案
我想,如果要使用强类型集线器,则必须在接口上定义所有客户端方法. AFAIK无法在强类型集线器和普通集线器之间混合匹配".如果您有这样的客户:
I think you must define all your client methods on the interface if you want to use strongly typed hub. AFAIK there is no way to "mix-and-match" between a strongly typed hub and a normal hub. If you have a client like this:
this.connection.on('receiveMessage', (message: string) => {
// Do things
});
this.connection.on('receiveData', (data: MyData, message: string) => {
// Do things
});
然后,如果要使用强类型集线器,则必须使用使用相同名称和签名(方法名不区分大小写)的方法定义强类型集线器接口:
Then if you want to use strongly typed hub, you must define your strongly typed hub interface with methods using the same names and signatures (method names are case-insensitive):
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!")
.整个要点是,您不必对客户端方法名称进行硬编码,并且可以对方法参数进行其他静态类型检查.
The advantage is that you can write await Clients.All.ReceiveMessage("Hello from server!")
instead of await Clients.All.SendAsync("ReceiveMessage", "Hello from server!")
. The whole point is that you don't have to hardcode the client method name and you get additional static type checking for the method parameters.
这篇关于SignalR:无法访问默认的集线器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!