我想通過在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個客戶端,並且網頁沒有收到消息? –
你可以做的是: 在啓動文件,當你'app.MapSignalR()',你可以'app.MapSignalR(新HubConfiguration {#如果 DEBUG EnableDetailedErrors =真 #ENDIF }); '這將在debigging模式下啓用詳細的錯誤。這樣,您可以通過在瀏覽器中打開控制檯來查看是否實際調用了客戶端方法。做到這一點,並分享輸出,請 –
集線器方法Send()不被調用(斷點沒有命中),所以我猜客戶端方法也沒有被調用:我沒有得到任何東西回來的視圖。 – user1472131