GilliVilla
GilliVilla

Reputation: 5090

Integrating SignalR with existing WebAPI endpoint

I have a Web API endpoint that creates a record and emits a successful 201 Created when the record is created.

Is it possible send a notification to a standalone HTML/JS web page that the record is created as it gets created using SignalR?

How can I create this publisher in the Web API and how to subscribe to it from the standalone webpage?

Upvotes: 0

Views: 566

Answers (1)

Mark C.
Mark C.

Reputation: 6450

Yes - it is possible so long as that browser has an active connection to the SignalR Hub.

You can use this code as a starting point. It assumes you have a SignalR Hub class named MessageHub. This broadcasts a message to all active SignalR clients.

[RoutePrefix("api/messaging")]
public class MessagingController : ApiController
{
    [Route("")]
    public void Post(Message message)
    {
        var notificationHub = GlobalHost.ConnectionManager.GetHubContext<MessageHub>();
        if (notificationHub != null)
        {
            try
            { 
               // create your record   
               notificationHub.Clients.All.creationSuccess(message);
            }
            catch (Exception ex)
            {
              // do a thing
            }
        }
    }
}

creationSuccess is the name of the function on the client side (JavaScript) which will handle the notification inside of the browser to which you're referring. Here's more information regarding the details of that

Upvotes: 3

Related Questions