AspNetCore Web API專案使用SignalR之用法

以AspNetCore建立的 Web API專案,使用Nuget套件:Microsoft.AspNetCore.SignalR的用法

以AspNetCore建立新 Web API專案,目標Framework為.NET 7.0,使用Nuget套件:Microsoft.AspNetCore.SignalR

首先建立Hub的Class:WindowsServiceHub.cs

namespace IPCWebApi.HubClass
{
	public class WindowsServiceHub : Hub
	{
		/// <summary>
		/// 傳送Windows Service狀態
		/// </summary>
		/// <param name="InputModel"></param>
		/// <returns></returns>
		public async Task SendWindowsServiceStatus(BooleanModel InputModel)
		{
			await Clients.All.SendAsync("SendWindowsServiceStatus", InputModel.Result);
		}
	}
}

在Controller裡新增:

/// <summary>
/// 傳送Windows Service狀態
/// </summary>
/// <param name="InputModel"></param>
/// <returns></returns>
[HttpPost]
[Route("SendWindowsServiceStatus")]
public async Task<IActionResult> SendWindowsServiceStatus(BooleanModel InputModel)
{
	await _hubContext.Clients.All.SendAsync("SendWindowsServiceStatus", InputModel.Result);
	return Ok();
}

最後在 Program.cs 裡的app.Run();前加進:

app.MapHub<WindowsServiceHub>("/windowsServiceHub");

再由另外的專案如windows service或windows console寫呼叫API的function內容如下僅供參考:

HttpClient client = SetHttpClient(URL);
client.Timeout = TimeSpan.FromSeconds(TimeOutSecond);

HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(InputModel), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(apiPath, httpContent);
response.EnsureSuccessStatusCode();