从控制器使用集线器的方法呢? [英] Use Hub methods from controller?

查看:164
本文介绍了从控制器使用集线器的方法呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用SignalR 2,我想不通我怎么可以使用例如集线器我从方法的控制器操作中。

I am using SignalR 2 and I can not figure out how I can use my Hub methods e.g from inside a controller action.

我知道我能做到以下几点:

I know I can do the following:

var hub = GlobalHost.ConnectionManager.GetHubContext<T>();
hub.Clients.All.clientSideMethod(param);

但是,直接执行该方法在客户端

But that executes the method directly on the client side.

如果我有我的服务器端 ClientSideMethod(参数)方法,我想从我的控制器相同的方式,当它从客户端叫调用内部的商业逻辑?

What if I have business logic inside my server side ClientSideMethod(param) method I want to call from my controller the same way as when it is called from the client side?

目前我使用公共静态无效ClientSideMethod(参数)我的轮毂内,并在该方法我用的那一刻起 IHubContext 的ConnectionManager

At the moment I use public static void ClientSideMethod(param) inside my hub and in that method I use the IHubContext from the ConnectionManager.

请问有没有更好的是这样做的?

以下不工作(在SignalR 2了吗?)

The following is not working (anymore in SignalR 2?):

var hubManager = new DefaultHubManager(GlobalHost.DependencyResolver);
instance = hubManager.ResolveHub(typeof(T).Name) as T;
instance.ClientSideMethod(param);

有我得到一个集线器而不是通过集线器管道创建不支持异常,访问客户时。

There I get a "Hub not created via Hub pipeline not supported" exception, when accessing the Clients.

推荐答案

由于我没有找到一个很好的解决方案:我使用@ michael.rp与一些改进方案:

As I did not find a "good solution" I am using @michael.rp's solution with some improvements:

我没有创建以下的基类:

I did create the following base class:

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;
        }
    }
}

然后在实际的集线器(例如公共类AdminHub:集线器&LT; AdminHub&GT; )我有(静态)方法如下所示:

And then in the actual Hub (e.g. public class AdminHub : Hub<AdminHub>) I have (static) methods like the following:

/// <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();
}

这篇关于从控制器使用集线器的方法呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆