【问题标题】:Contacting the method on the server from client code从客户端代码联系服务器上的方法
【发布时间】:2018-09-30 16:20:58
【问题描述】:

我是第一次尝试使用 SignalR,想将它添加到我的项目中。

我现在的问题是我无法从服务器获取消息。我收到此错误:

TypeError: signalRhub.Test is not a function

我对脚本的引用如下所示(似乎可行):

<script src="~/Scripts/jquery.signalR-2.3.0.js"></script>
<script src="~/Scripts/jquery.signalR-2.3.0.min.js"></script>
<script src='~/signalr/js'></script>

这是我的客户端代码:

<script>
    $(function () {
        var signalRhub = $.connection.hubSignalR;
        console.log(signalRhub);
        //Start connection
        $.connection.hub.start(function () {
            signalRhub.Test(function (response) {
                 alert("Response from server: " + response);
                //$("#testDiv").html(response);                
            });            
        });
    });
</script>

这是我的服务器类定义,以及我试图调用的方法(找不到):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;

    namespace AuthSys.SignalRhub
    {
        public class HubSignalR : Hub
        {
            public string Test()
            {
                return "Success from server";
            }
        }
    }

------------------- 附加信息 ---------------

我附上了我的 Firefox 控制台的屏幕截图。在我的客户端代码中,您会注意到以下代码:

console.log(signalRhub);

这就是您在 Firefox 控制台中看到的内容。看着名为connection 的孩子,似乎已经建立了联系。在这里,您可以看到它生成的 URL 等。查看 serverchild(扩展了 2 个级别),看起来它找到了服务器上的 Test() 方法。

我的 Startup.cs 看起来像这样(如果有任何重要性):

using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(AuthSys.Startup))]
namespace AuthSys
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
            app.MapSignalR();
        }
    }
}

任何人都可能知道我的问题是什么?

我期望(试图做的)是在我的屏幕上得到一个警报,带有字符串:

Success from server

在服务器上的 C# 类中可以看到。

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-5 signalr


    【解决方案1】:

    更改您的 C# 代码以发布您的消息

    public string Test() {
       //Clients.Client("ToClientId").TestMessages("Message");//send messages to specific user
       Clients.All.TestMessages("Message"); //send messages to all user
    }
    

    发送方法Javascript

    signalRhub.server.test();//Note you didn't have created parameter, but you can create them
    

    Javascript 这样的方法

    signalRhub.client.TestMessages = function (response) {
        alert("Response from server: " + response);
    };
    

    【讨论】:

    • 感谢您的帮助。注意:signalRhub.server.Test() 中的 Test();必须更改为小写才能正常工作。所以一定是:signalRhub.server.test();
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-18
    • 1970-01-01
    • 2011-09-09
    相关资源
    最近更新 更多