ASP.NET 空网站中的 SignalR 无法正常工作

SignalR in ASP.NET empty website not working

我对 SignalR 这个词还很陌生。我试图将 signalR 配置到我的空网站中并添加了以下代码。

在App_Code

  using Microsoft.Owin;
  using Owin;

  [assembly: OwinStartup(typeof(Super.App_Code.Startup))]

  namespace Super.App_Code
  {
     public class Startup
     {
         public static void Configuration(IAppBuilder app)
         {
             app.MapSignalR();

         }
     }
  }

和集线器class里面App_Code

namespace Super.App_Code
{
[HubName("toastHub")]
 public class ToastHub : Hub
{
    public void BroadcastToast(string type ,string msg)
    {
        Clients.All.sendToast(type , msg);
    }
}
}

并在 Default.aspx

<head runat="server">
<title></title>
<link rel="stylesheet" href="content/toastr.min.css" />

<script src="Scripts/jquery-1.6.4.js" type="text/javascript"></script>
<script src="Scripts/jquery.signalR-2.4.1.js" type="text/javascript"></script>
<script src="Scripts/toastr.min.js" type="text/javascript"></script>
<script src="signalr/hubs" type="text/javascript"></script>

<script type="text/javascript">

    $(document).ready(function () {

        $("#SuccessLink").click(function () {
            console.log("Success Click");
            $.connection.toastHub.client.broadcastToast('success', 'you have done');
        });

        $("#ErrorLink").click(function () {
            console.log("Error Click");
            $.connection.toastHub.client.broadcastToast("error", "you have not done");
        });

        $.connection.hub.start().done(function () {
            console.log('SignalR connected');
        })
        .fail(function (data) {
            console.log('SignalR failed to connect: ' + data);
        });

        $.connection.toastHub.client.sendToast = function (type, msg) {
            console.log("sendToast Called");
            toastr[type](msg);
        };
    });
 </script>
 </head>
 <body>
 <form id="form1" runat="server">
    <div>
        <a id="SuccessLink" style="color: lightgreen">Success Toast</a><br />
        <a id="ErrorLink" style="color: red">Error Toast</a>
    </div>

  </form>
  </body>
  </html>

但是当我 运行 我的网站 javascript 控制台在点击其中一个标签时会说这个

  SignalR connected
  Default.aspx:20 Success Click
  Default.aspx:21 Uncaught TypeError: $.connection.toastHub.client.broadcastToast is not a function
      at HTMLAnchorElement.<anonymous> (Default.aspx:21)
      at HTMLAnchorElement.handle (jquery-1.6.4.js:3001)
      at HTMLAnchorElement.eventHandle (jquery-1.6.4.js:2635)

我做错了什么请帮助我任何帮助都会很棒。我是 SignalR 的新手。

signalr/hub

if (typeof ($.signalR) !== "function") {
    throw new Error("SignalR: SignalR is not loaded. Please ensure         jquery.signalR-x.js is referenced before ~/signalr/js.");
}

var signalR = $.signalR;

function makeProxyCallback(hub, callback) {
    return function () {
        // Call the client hub method
        callback.apply(hub, $.makeArray(arguments));
    };
}

function registerHubProxies(instance, shouldSubscribe) {
    var key, hub, memberKey, memberValue, subscriptionMethod;

    for (key in instance) {
        if (instance.hasOwnProperty(key)) {
            hub = instance[key];

            if (!(hub.hubName)) {
                // Not a client hub
                continue;
            }

            if (shouldSubscribe) {
                // We want to subscribe to the hub events
                subscriptionMethod = hub.on;
            } else {
                // We want to unsubscribe from the hub events
                subscriptionMethod = hub.off;
            }

            // Loop through all members on the hub and find client hub functions to subscribe/unsubscribe
            for (memberKey in hub.client) {
                if (hub.client.hasOwnProperty(memberKey)) {
                    memberValue = hub.client[memberKey];

                    if (!$.isFunction(memberValue)) {
                        // Not a client hub function
                        continue;
                    }

                    // Use the actual user-provided callback as the "identity" value for the registration.
                    subscriptionMethod.call(hub, memberKey, makeProxyCallback(hub, memberValue), memberValue);
                }
            }
        }
    }
}

$.hubConnection.prototype.createHubProxies = function () {
    var proxies = {};
    this.starting(function () {
        // Register the hub proxies as subscribed
        // (instance, shouldSubscribe)
        registerHubProxies(proxies, true);

        this._registerSubscribedHubs();
    }).disconnected(function () {
        // Unsubscribe all hub proxies when we "disconnect".  This is to ensure that we do not re-add functional call backs.
        // (instance, shouldSubscribe)
        registerHubProxies(proxies, false);
    });

    proxies['toastHub'] = this.createHubProxy('toastHub'); 
    proxies['toastHub'].client = { };
    proxies['toastHub'].server = {
    };

    return proxies;
};

signalR.hub = $.hubConnection("/signalr", { useDefaultPath: false });
$.extend(signalR, signalR.hub.createHubProxies());

}(window.jQuery, window));

你的 SignalR 项目没有正确初始化某些东西,我想访问 hubContext 应该在你的 startup.cs 中有一个依赖注入器。但是使用 DI 为 SignalR 进行上下文注入是一个高级问题。

但是,请尝试这个最小的示例,如果它适合您的话:https://github.com/bezzad/MVC-SignalR-2

在我看来,您只需将对 broadcastToast 的调用从客户端更改为服务器即可。由于该方法位于 Hub 中,因此需要服务器。

$.connection.toastHub.client.broadcastToast 到 $.connection.toastHub.server.broadcastToast