Ответ 1
Я решил свою проблему, изменив строку::
<script src="/signalr/hubs"></script>
к
<script src="~/signalr/hubs"></script>
Я могу получить tutorial для работы в новом проекте, но не в моем существующем проекте.
Мой проект - это веб-приложение ASP.Net MVC 4 со следующим атрибутом в файле 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) { ....
потому что chat имеет значение null, поскольку предыдущая строка не нашла chatHub:
var chat = $.connection.chatHub;
Кто-нибудь знает, что случилось с моим кодом?
UPDATE
Я решил свою проблему, изменив строку::
<script src="/signalr/hubs"></script>
to
<script src="~/signalr/hubs"></script>
Я решил свою проблему, изменив строку::
<script src="/signalr/hubs"></script>
к
<script src="~/signalr/hubs"></script>
Кроме того, причина, по которой /signalr/hubs не генерируется, не забудьте Map SignalR в настройке запуска OWIN.
public class Startup
{
public void Configuration(IAppBuilder appBuilder){
...
appBuilder.MapSignalR();
...
}
...
В моем случае это было потому, что мой класс ChatHub не был опубликован.
У меня была аналогичная проблема, когда файл хабов не генерировался. Похоже, что OP был в соответствии с шагами здесь. Способ, которым я исправил проблему, связан с включением jquery. Учебник, связанный ниже, был написан с помощью jquery 1.6.4 и jquery-signalr версии 2.1.0. Когда Visual Studio сгенерировала для меня папку Scripts, она использовала jQuery версии 1.10.2 и jquery-signalr версии 2.0.2.
Как я исправил это, просто отредактировать файл index.html. Обратите внимание, что вы можете использовать окно консоли Chrome javascript Ctrl + Shift + J, чтобы увидеть ошибки.
Я хочу добавить, что в файле ReadR Readme есть заметки об этой проблеме. А также, если ваша страница signalR находится в PartialView, на главной странице должен быть размещен script.
Please see http://go.microsoft.com/fwlink/?LinkId=272764 for more information on using SignalR.
Upgrading from 1.x to 2.0
-------------------------
Please see http://go.microsoft.com/fwlink/?LinkId=320578 for more information on how to
upgrade your SignalR 1.x application to 2.0.
Mapping the Hubs connection
----------------------------
To enable SignalR in your application, create a class called Startup with the following:
using Microsoft.Owin;
using Owin;
using MyWebApplication;
namespace MyWebApplication
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
Getting Started
---------------
See http://www.asp.net/signalr/overview/getting-started for more information on how to get started.
Why does ~/signalr/hubs return 404 or Why do I get a JavaScript error: 'myhub is undefined'?
--------------------------------------------------------------------------------------------
This issue is generally due to a missing or invalid script reference to the auto-generated Hub JavaScript proxy at '~/signalr/hubs'.
Please make sure that the Hub route is registered before any other routes in your application.
In ASP.NET MVC 4 you can do the following:
<script src="~/signalr/hubs"></script>
If you're writing an ASP.NET MVC 3 application, make sure that you are using Url.Content for your script references:
<script src="@Url.Content("~/signalr/hubs")"></script>
If you're writing a regular ASP.NET application use ResolveClientUrl for your script references or register them via the ScriptManager
using a app root relative path (starting with a '~/'):
<script src='<%: ResolveClientUrl("~/signalr/hubs") %>'></script>
If the above still doesn't work, you may have an issue with routing and extensionless URLs. To fix this, ensure you have the latest
patches installed for IIS and ASP.NET.
Для меня было решено переустановить все пакеты и восстановить все dependecies.
Откройте консоль powershell для nuget и используйте эту команду.
Update-Package -Reinstall