我正在使用 SignalR 2,但我无法弄清楚如何使用我的 Hub 方法,例如从 Controller 操作内部。
我知道我可以做到以下几点:
var hub = GlobalHost.ConnectionManager.GetHubContext<T>();
hub.Clients.All.clientSideMethod(param);
但这会直接在客户端执行该方法。
如果我的服务器端有业务逻辑怎么办
ClientSideMethod(param)
我想从我的 Controller 调用的方法与从客户端调用它时的方法相同吗?目前我使用
public static void ClientSideMethod(param)
在我的集线器内,在这种方法中,我使用 IHubContext
来自 ConnectionManager
.这样做没有更好的办法吗?
以下不起作用(在 SignalR 2 中不再起作用?):
var hubManager = new DefaultHubManager(GlobalHost.DependencyResolver);
instance = hubManager.ResolveHub(typeof(T).Name) as T;
instance.ClientSideMethod(param);
访问客户端时,出现“不支持通过 Hub 管道创建的 Hub”异常。
最佳答案
它可能会创建一个“帮助器”类来实现您的业务规则并由您的集线器和 Controller 调用:
public class MyHub : Hub
{
public void DoSomething()
{
var helper = new HubHelper(this);
helper.DoStuff("hub stuff");
}
}
public class MyController : Controller
{
public ActionResult Something()
{
var hub = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
var helper = new HubHelper(hub);
helper.DoStuff("controller stuff");
}
}
public class HubHelper
{
private IHubConnectionContext hub;
public HubHelper(IHubConnectionContext hub)
{
this.hub = hub;
}
public DoStuff(string param)
{
//business rules ...
hub.Clients.All.clientSideMethod(param);
}
}
关于asp.net - 使用 Controller 中的 Hub 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17896739/