简体   繁体   中英

SignalR and WebAPI

I want to send notifications to web page, which is a client WebAPI . So, I have 2 solutions, Asp.Net MVC application and WebAPI application. I have added SignalR nuget to both. WebAPI part has the following code:

public class ProgressHub : Hub
{
    public void Notification(string message)
    {
        Clients.Caller.onProgressNotification(message);
    }
}


private void SendMessage(string message)
{
    var context = Microsoft.AspNet.SignalR
        .GlobalHost.ConnectionManager.GetHubContext<Hubs.ProgressHub>();
    context.Clients.All.onProgressNotification(message);
}

and then call it from my controller Action:

public async Task<IHttpActionResult> ZonalPost()
{
    SendMessage("Start");
    // my long operation
    SendMessage("Scan complete");
    // my long operation
    SendMessage("Convert complete");
    // my long operation

And in my web application (client part):

<script src="~/Scripts/jquery.signalR-2.2.2.min.js"></script>
<script src="~/signalr/hubs"></script>
<script>
    $(function () {
        var progress = $.connection.progressHub;

        progress.client.onProgressNotification = function (message) {
            console.log(message);
        };
    });

but I got an error

430 Uncaught TypeError: Cannot read property 'client' of undefined

Why and how to solve?

You may need to use something like the following:

$(function () {
    $.connection.hub.url = '<yourbackendurl>';
    var connection = $.hubConnection();
    var progress = connection.createHubProxy('progressHub');
    progress.on('onProgressNotification', function(message) {
        console.log(message);
    });
    connection.start()
        .done(function(){ console.log('Now connected, connection ID=' + connection.id); })
        .fail(function(){ console.log('Could not connect'); });
});

See the docs on using SignalR without the generated proxy . Note that you also need to specify the server URL if you're connecting to a different server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM