このチュートリアルを新しいプロジェクトで動作させることはできますが、既存のプロジェクトでは動作しません。
私のプロジェクトは、web.config ファイルに次の属性を持つ ASP.Net MVC 4 Web アプリケーションです。
<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 が見つからなかったため、chat が null であるためです。
var chat = $.connection.chatHub;
私のコードの何が問題なのか誰か知っていますか?
アップデート
行を変更して問題を解決しました::
<script src="/signalr/hubs"></script>
に
<script src="~/signalr/hubs"></script>