2015-09-07 18 views
3

我想通過在mvc應用程序中使用SignalR向所有客戶端廣播消息。我遇到的問題是,當我使用此代碼GlobalHost.ConnectionManager.GetHubContext <MyHub>()將返回一個沒有客戶端的上下文

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

所以你是說上下文說有0個客戶端,並且網頁沒有收到消息? –

+1

你可以做的是: 在啓動文件,當你'app.MapSignalR()',你可以'app.MapSignalR(新HubConfiguration {#如果 DEBUG EnableDetailedErrors =真 #ENDIF }); '這將在debigging模式下啓用詳細的錯誤。這樣,您可以通過在瀏覽器中打開控制檯來查看是否實際調用了客戶端方法。做到這一點,並分享輸出,請 –

+0

集線器方法Send()不被調用(斷點沒有命中),所以我猜客戶端方法也沒有被調用:我沒有得到任何東西回來的視圖。 – user1472131

回答

2

你的概念有點混淆。

問題是,你不能從後端的另一個地方調用集線器方法,所以你不能打電話給他Send hub mehod,但從任何地方,但除了連接的客戶端(在你的情況下網站)。

當你做Context.Clients.doSomething()你實際上叫做SignalR的客戶端部分,並告訴它執行JavaScript方法doSomething()(如果存在的話)。

因此,從控制你的電話應該是context.Clients.All.addNewMessageToPage(message);

希望這有助於。祝你好運!

+0

如果這對你有所幫助,請考慮提高它。祝你好運! –

相關問題