c# – 使用Web API作为SignalR服务器并从Windows服务中使用它

我在Web应用程序通过使用.net远程处理与Windows服务通信的同一服务器上有一个Web应用程序和一个Windows服务. Windows服务检查与LDAP的连接是否正常,然后返回true,否则抛出异常. Windows服务的状态在网站上更新.

现在基础设施将会发生变化. Web应用程序将在Azure上运行,Windows服务将保留在客户端的计算机上(因为LDAP位于客户端).我需要像现在一样更新Web应用程序的状态.我已经介绍了Web API作为Web应用程序和Windows服务之间的中间层.

我无法找到更好的解决方案来实现这种情况.我考虑使用SignalR或Akka.remote.

我到目前为止所想的,如果我在Web API和Windows服务中使用SignalR并执行以下操作:

> Web应用程序使用Web API方法
> Web API方法使用SignalR并向Windows服务发送信号
> Windows服务检查LDAP连接并调用Web API方法以返回状态.

注意:我不知道如何将Windows服务作为客户端,并使其能够监听web api是否向其发送信号,因为我不需要为Windows服务使用自托管.我们可以使用web api,因为它已经托管了.

它可以实现吗?或者有更好的解决方案吗?请帮忙.
提前致谢.

解决方法:

我能够解决这个问题,并得到了解决方案.

Web API中startup.cs中的SignalR配置

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.MapSignalR("/signalr", new Microsoft.AspNet.SignalR.HubConfiguration());
    }
}

在Web API添加中心

    public class ServiceStatusHub : Hub
    {
        private static IHubContext hubContext = 
        GlobalHost.ConnectionManager.GetHubContext<ServiceStatusHub>();

        public static void GetStatus(string message)
        {
            hubContext.Clients.All.acknowledgeMessage(message);
        }

    }

在Web API操作方法中

    public IEnumerable<string> Get()
    {
        // Query service to check status
        ServiceStatusHub.GetStatus("Please check status of the LDAP!");
        return new string[] { "val1", "val2" };
    }

在控制台应用程序中添加SignalR Client

public class SignalRMasterClient
{
    public string Url { get; set; }
    public HubConnection Connection { get; set; }
    public IHubProxy Hub { get; set; }

    public SignalRMasterClient(string url)
    {
        Url = url;
        Connection = new HubConnection(url, useDefaultUrl: false);
        Hub = Connection.CreateHubProxy("ServiceStatusHub");
        Connection.Start().Wait();

        Hub.On<string>("acknowledgeMessage", (message) =>
        {
            Console.WriteLine("Message received: " + message);

            /// TODO: Check status of the LDAP
            /// and update status to Web API.
        });
    }

    public void SayHello(string message)
    {
        Hub.Invoke("hello", message);
        Console.WriteLine("hello method is called!");
    }

    public void Stop()
    {
        Connection.Stop();
    }

}

在Program.cs类中

class Program
{
    static void Main(string[] args)
    {
        var client = new SignalRMasterClient("http://localhost:9321/signalr");

        // Send message to server.
        client.SayHello("Message from client to Server!");

        Console.ReadKey();

        // Stop connection with the server to immediately call "OnDisconnected" event 
        // in server hub class.
        client.Stop();
    }
}

现在在postman中运行Web API并运行控制台应用程序.将建立双向通信.

注意:下面的代码是修复了控制台关闭时的问题,它没有立即触发OnDisconnected事件.

    public void Stop()
    {
        Connection.Stop();
    }

Check the image showing result.

上一篇:javascript – SignalR,每个事件有多个事件处理程序


下一篇:c# – 如何将SignalR与Xamarin一起使用