SignalR hubclass in classlibrary

血红的双手。 提交于 2020-01-16 01:55:08

问题


I have a signalr hubclass in a classlibrary

and when i use that hubclass in my webapplication referencing that class library with below javascript code, it does not work,

$(function () {

    var chat = $.connection.notificationHub;

    chat.client.newMessage = function (message) {
        alert(message);

        $('#messages').append('<li><strong>' +  message + '</strong>: </li>');
    };
    $.connection.hub.start();
});

回答1:


You need an event to trigger your method in Hub class. See below example:

NotificationHub in the class library

public class NotificationHub : Hub
{
    public void Send(string message)
    {
        Clients.All.newMessage(message);
    }
}

Web application

<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<ul id="messages"></ul>

   <script src="~/Scripts/jquery-1.10.2.min.js"></script>
   <script src="~/Scripts/jquery.signalR-2.0.1.min.js"></script>
   <script src="signalr/hubs"></script>

    <script>
        $(function () {
            var chat = $.connection.notificationHub;
            chat.client.newMessage = function (data) {
                //alert(data);
                $('#messages').append('<li><strong>' + data + '</strong>: </li>');
            };
            $('#message').focus();
            $.connection.hub.start().done(function () {
                console.log("Connected");
                $('#sendmessage').click(function () {
                    chat.server.send($('#message').val());
                    $('#message').val('').focus();
                });
            });
        });
    </script>

Note

Because you the hubclass is in the class library, you need to install Microsoft ASP.NET SignalR package in it. You also need to install it in the webapplication. Then add hubclass reference to webapplication. Add app.MapSignalR() in your Startup class, like below:

public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
            app.MapSignalR();
        }
    }


来源:https://stackoverflow.com/questions/20795982/signalr-hubclass-in-classlibrary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!