简体   繁体   English

将SignalR与现有WebAPI端点集成

[英]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. 我有一个Web API端点,该端点创建一条记录并在创建记录时发出成功的201 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? 是否可以向独立的HTML / JS网页发送一条通知,通知该记录是在使用SignalR创建记录时创建的?

How can I create this publisher in the Web API and how to subscribe to it from the standalone webpage? 如何在Web API中创建此发布者,以及如何从独立网页进行订阅?

Yes - it is possible so long as that browser has an active connection to the SignalR Hub. 是的-只要该浏览器与SignalR Hub处于活动连接,就可以。

You can use this code as a starting point. 您可以使用此代码作为起点。 It assumes you have a SignalR Hub class named MessageHub . 假定您有一个名为MessageHub的SignalR Hub类。 This broadcasts a message to all active SignalR clients . all active SignalR clients消息广播到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. creationSuccess是客户端(JavaScript)上函数的名称,它将处理您所引用的浏览器内部的通知。 Here's more information regarding the details of that 这是有关该细节的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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