我遵循了这个简单的tutorial并设法使用 signalR 创建一个测试 Web 应用程序。但是当我尝试使用 ASP.NET 网站重新创建它,然后浏览 html 页面时,出现以下错误:
TypeError: $.connection is undefined
var chat = $.connection.chatHub;
如果这很重要的话,这是我的项目的结构:
根据我的发现,在 web.config 中将 runAllManagedModulesForAllRequests
设置为 true 是必要的,所以我已经这样做了。另外,我遵循的教程有点过时,因为我使用 VS 2010(即 .NET Framework 4),它仅与 SignalR v 1.1.3 兼容。
为什么我无法在网站中使用此功能,但在网络应用程序中却可以完美使用?
更新:
一个解决方案(我认为是正确的)建议
Put my code behind file in a seperate .cs file and put that cs file in App_Code folder
所以我尝试将 html 文件更改为 .aspx 文件。这样我就有了一个代码隐藏文件(即 .aspx.cs),但我对移动代码隐藏文件的含义感到困惑,因为将我的 .aspx 文件嵌套到驻留在 App_Code 文件夹中的 .aspx.cs 文件不是允许。
上面引用的答案是什么意思?
更新:
这是我在 HTMLPage.htm 中的脚本引用以及 main 函数。
<!--Reference the jQuery library. -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!--Reference the SignalR library. -->
<script src="/Scripts/jquery.signalR-1.1.3.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>
最佳答案
当出现问题时,您应该始终检查控制台 - 在您的情况下,页面根本找不到对 SignalR 脚本和/signalr/hubs 的引用(控制台中是这样说的)。如果将网址更改为“/WebSite18/Scripts/jquery.signalR-1.1.3.js”和“/Website18/signalr/hubs”,它将起作用。
关于c# - SignalR 无法在网站中工作,但可以在 Web 应用程序中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20311792/