GlobalHost.ConnectionManager.GetHubContext <MyHub>()将返回没有客户端的上下文

use*_*131 5 c# model-view-controller signalr

我试图通过在mvc应用程序中使用SignalR向所有客户端广播消息。我遇到的问题是当我使用此代码时

var context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
Run Code Online (Sandbox Code Playgroud)

上下文没有客户端,因此不会广播该消息。下面是我正在使用的代码的简化版本。我想念什么吗?谢谢

风景:

@using System.Web.UI.WebControls
@using MyApp.Models
@model MyApp.Models.MyModel

<form class="float_left" method="post" id="form" name="form">
    <fieldset>
        Username: <br/>
        @Html.TextBoxFor(m => m.Username, new { Value = Model.Username })
        <br/><br/>
        <input id="btnButton" type="button" value="Subscribe"/>
        <br/><br/>
        <div id="notificationContainer"></div>
    </fieldset>
</form>
@section scripts {
    <script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
    <script src="~/signalr/hubs"></script>
    <script>
        $(function () {
            var notification = $.connection.notificationHub;
            notification.client.addNewMessageToPage = function (message) {
                $('#notificationContainer').append('<strong>' + message + '</strong>');
            };

            $.connection.hub.start();

        });

        $("#btnButton").click(function () {
            $.ajax({
                url: "/Home/Subscribe",
                data: $('#form').serialize(),
                type: "POST"
            });
        });

    </script>
}
Run Code Online (Sandbox Code Playgroud)

集线器:

namespace MyApp.Hubs
{
    public class NotificationHub : Hub
    {
        public void Send(string message)
        {
            Clients.All.addNewMessageToPage(message);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

控制器:

namespace MyApp.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public void Subscribe()
        {
            var message = "" // get message...

            var context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
            context.Clients.All.Send(message);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

rad*_*tei 5

您对概念有些困惑。

问题是您不能从后端的另一个位置调用集线器方法,因此您不能Send从连接的客户端(在您的情况下为网站)以外的任何地方调用集线器方法。

当您执行操作时,Context.Clients.doSomething()您实际上调用的客户端部分,SignalR并告诉它执行JavaScript方法(doSomething()如果存在)。

因此,您从控制器拨打的电话应为 context.Clients.All.addNewMessageToPage(message);

希望这可以帮助。祝你好运!