Asp.net-Mvc-4

signalR : 未生成 /signalr/hubs

  • July 2, 2013

我可以讓本教程在一個新項目中工作,但不能在我現有的項目中工作。

我的項目是一個 ASP.Net MVC 4 Web 應用程序,在 web.config 文件中具有以下屬性:

<appSettings>
 <add key="webpages:Enabled" value="true"/>
</appSettings>

這是因為我的應用程序是單頁應用程序,它在客戶端使用 AngularJS。我的應用程序中唯一的頁面是 index.cshtml,我在其中添加了 signalR 的相關程式碼:

<!-- signalR chat -->
<script src="~/Scripts/jquery.signalR-1.0.0.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="/signalr/hubs"></script>
<!--Add script to update the page and send messages.--> 
<script type="text/javascript">
   $(function () {
       // Declare a proxy to reference the hub. 
       var chat = $.connection.chatHub;
       // Create a function that the hub can call to broadcast messages.
       chat.client.broadcastMessage = function (name, message) {
           // Html encode display name and message. 
           var encodedName = $('<div />').text(name).html();
           var encodedMsg = $('<div />').text(message).html();
           // Add the message to the page. 
           $('#discussion').append('<li><strong>' + encodedName
               + '</strong>:  ' + encodedMsg + '</li>');
       };
       // Get the user name and store it to prepend to messages.
       $('#displayname').val(prompt('Enter your name:', ''));
       // Set initial focus to message input box.  
       $('#message').focus();
       // Start the connection.
       $.connection.hub.start().done(function () {
           $('#sendmessage').click(function () {
               // Call the Send method on the hub. 
               chat.server.send($('#displayname').val(), $('#message').val());
               // Clear text box and reset focus for next comment. 
               $('#message').val('').focus();
           });
       });
   });
</script>

然後我得到了 ChatHub.cs 文件:

public class ChatHub : Hub
{
   public void Send(string name, string message)
   {
       // Call the broadcastMessage method to update clients.
       Clients.All.broadcastMessage(name, message);
   }
}

最後在 global.asax 中:

protected void Application_Start()
   {
       RouteTable.Routes.MapHubs();
       BundleConfig.RegisterBundles(BundleTable.Bundles);
   }

當我執行應用程序時,不會生成 /signalr/hubs 文件。我在請求文件時收到 404,它線上上崩潰:

chat.client.broadcastMessage = function (name, message) { ....

因為上一行沒有找到chatHub,所以聊天為空:

var chat = $.connection.chatHub;

有誰知道我的程式碼有什麼問題?

更新

我通過更改行解決了我的問題::

<script src="/signalr/hubs"></script>

<script src="~/signalr/hubs"></script>

我通過更改行解決了我的問題::

<script src="/signalr/hubs"></script>

<script src="~/signalr/hubs"></script>

引用自:https://stackoverflow.com/questions/17422023