Asp.net
使用控制器中的 Hub 方法?
我正在使用 SignalR 2,但我無法弄清楚如何使用我的 Hub 方法,例如從控制器操作內部。
我知道我可以做到以下幾點:
var hub = GlobalHost.ConnectionManager.GetHubContext<T>(); hub.Clients.All.clientSideMethod(param);但這會直接在客戶端執行該方法。
如果我的伺服器端
ClientSideMethod(param)方法中有業務邏輯,我想從控制器呼叫與從客戶端呼叫它時相同的方式怎麼辦?目前我
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);訪問客戶端時,出現“不支持通過集線器管道創建集線器”異常。
由於我沒有找到“好的解決方案”,我正在使用@michael.rp 的解決方案並進行了一些改進:
我確實創建了以下基類:
public abstract class Hub<T> : Hub where T : Hub { private static IHubContext hubContext; /// <summary>Gets the hub context.</summary> /// <value>The hub context.</value> public static IHubContext HubContext { get { if (hubContext == null) hubContext = GlobalHost.ConnectionManager.GetHubContext<T>(); return hubContext; } } }然後在實際的集線器(例如
public class AdminHub : Hub<AdminHub>)中,我有如下(靜態)方法:/// <summary>Tells the clients that some item has changed.</summary> public async Task ItemHasChangedFromClient() { await ItemHasChangedAsync().ConfigureAwait(false); } /// <summary>Tells the clients that some item has changed.</summary> public static async Task ItemHasChangedAsync() { // my custom logic await HubContext.Clients.All.itemHasChanged(); }
它可能會創建一個“幫助器”類來實現您的業務規則並由您的集線器和控制器呼叫:
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); } }