Chr*_*Fin 17 asp.net asp.net-mvc signalr signalr-hub
我正在使用SignalR 2,我无法弄清楚如何使用我的Hub方法,例如在控制器动作中.
我知道我可以做到以下几点:
var hub = GlobalHost.ConnectionManager.GetHubContext<T>();
hub.Clients.All.clientSideMethod(param);
Run Code Online (Sandbox Code Playgroud)
但是直接在客户端执行该方法.
如果我的服务器端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);
Run Code Online (Sandbox Code Playgroud)
在访问客户端时,我得到"不通过Hub管道创建的集线器不受支持"异常.
mic*_*lrp 12
它可能会创建一个实现业务规则的"帮助程序"类,并由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);
}
}
Run Code Online (Sandbox Code Playgroud)
Chr*_*Fin 11
由于我没有找到"好的解决方案",我正在使用@ 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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后在实际的Hub(例如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();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10512 次 |
最近记录: |