0

我为 POC 创建了一个示例 signalR。我想从 Global.asax 调用一个集线器方法并将一个字符串值传递给客户端。我的消息中心是:-

[HubName("messageHub")]
public class MessageHub : Hub
{
    public static IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MessageHub>();
    public void Message()
    {

        /*
         * services and updates the messages
        * property on the PushMessage hub
        */
        //IHubContext context = GlobalHost.ConnectionManager.GetHubContext<SignalR_Error_Logging.Models.ErrorModel>();
        List<GenerateError.Repository.ErrorModel> model = ErrorRepository.GetError();
        context.Clients.pushMessages(model[0].ErrorMessage);

    }

我在 layout.cshtml 中定义了两个脚本

<script type="text/javascript" src="../../Scripts/jquery-1.6.4.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.signalR-0.5.3.js"></script>

我的 Index.html 如下:-

    @{
    ViewBag.Title = "Receive Error message";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="/signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
    $(function () {
        var myHub = $.connection.messageHub;
        myHub.pushMessages = function (value) {
            console.log('Server called addMessage(' + value + ')');
            $("#messages").append("<li>" + value + "</li>");
        };
        $("#btnMessage").click(function () {

            myHub.message();
        });
        $.connection.hub.start().done(function () { alert("Now connected!"); }).fail(function () { alert("Could not Connect!"); });
    });

</script>
<h2>Receive Error Messages</h2>
<ul id="messages"></ul>
<input type="button" id="btnMessage" value="Get Error" />

在 Global.asax 我写过

SignalR_Error_Logging.SignalRHub.MessageHub hub = new SignalRHub.MessageHub();
        hub.Message();

在 Application_Start();

我无法在我的 UI(即 Index.cshtml)中显示消息。

我尝试过的事情:-

  • 将应用程序作为 IIS 运行。
  • 改变创建 HubContext 的方式。

        IHubContext _context = GlobalHost.ConnectionManager.GetHubContext<MessageHub>();
    context.Clients.notify("Hello world");
    
  • if (Clients != null) { Clients.shootErrorMessage(message); this.Clients.shootErrorMessage(message); }

  • 通过 Stackoverflow的链接从系统中的其他地方调用 SignalR 集线器客户端

有什么建议???

当我通过在 Index.html 中创建一个按钮来调用我的集线器方法时,它工作正常。

抱歉没有正确地提出我的问题!!

4

2 回答 2

2

我发现,调用集线器的方式不正确。目前我已经修改了 Global.asax 中的代码:-

 private void CallSignalR()
    {
        var context = SignalR.GlobalHost.ConnectionManager.GetHubContext<SignalR_Error_Logging.SignalRHub.MessageHub>();
        List<GenerateError.Repository.ErrorModel> err = GenerateError.Repository.ErrorRepository.GetError();
        foreach (var item in err)
        {
            item.ErrorDescription = item.ErrorDescription + DateTime.Now.ToString();
        }
        context.Clients.pushMessages(err);


    }

现在工作得很好:)

还在寻找更好的选择!!!!

于 2012-10-12T13:33:40.467 回答
1

这永远不会奏效。Global.asax 中的 Application_Start() 在 AppDomain 的生命周期内只调用一次。它发生在网站启动时,此时尚未连接任何客户端(因为网站尚未完全初始化),因此您无法通过 SignalR 发送消息。

于 2012-10-11T12:24:46.987 回答