GlobalHost.ConnectionManager.GetHubContext<MyHub>() 将 return 一个没有客户端的上下文

GlobalHost.ConnectionManager.GetHubContext<MyHub>() will return a context with no clients

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

var context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();

上下文没有客户端,所以不会广播消息。下面是我正在使用的代码的简化版本。我错过了什么?谢谢

观点:

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

枢纽:

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

控制者:

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

你的概念有点混乱。

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

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

所以你来自控制器的调用应该是context.Clients.All.addNewMessageToPage(message);

希望这对您有所帮助。祝你好运!