我已經能夠解決這個問題,並得到了解決方案。
啓動時的SignalR配置。CS中的Web API
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR("/signalr", new Microsoft.AspNet.SignalR.HubConfiguration());
}
}
在網頁API加樞
public class ServiceStatusHub : Hub
{
private static IHubContext hubContext =
GlobalHost.ConnectionManager.GetHubContext<ServiceStatusHub>();
public static void GetStatus(string message)
{
hubContext.Clients.All.acknowledgeMessage(message);
}
}
在網頁API操作方法
public IEnumerable<string> Get()
{
// Query service to check status
ServiceStatusHub.GetStatus("Please check status of the LDAP!");
return new string[] { "val1", "val2" };
}
在控制檯應用程序添加SignalR客戶
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();
}
}
現在運行在郵遞員在Web API,也運行控制檯程序。雙向溝通將建立。
注意:下面的代碼是關於控制檯關閉時不立即觸發OnDisconnected事件的問題的修復。
public void Stop()
{
Connection.Stop();
}
Check the image showing result.
嗨弗雷德漢,感謝您的回覆。如果Windows服務已關閉,那麼web api如何知道? –