CompServClient.cs 1.0 KB

1234567891011121314151617181920212223242526272829303132
  1. using System.Net;
  2. using static CompServ.CompServConst;
  3. namespace CompServ.ClientLibrary;
  4. public abstract class CompServClient(string server, string apiCheckAlive, string aliveMessage)
  5. {
  6. protected readonly Uri ServerUri = new Uri(server);
  7. public async Task<bool> CheckAliveAsync(int timeoutInSecond = 1)
  8. {
  9. try
  10. {
  11. var httpRequest = new HttpRequestMessage(HttpMethod.Get, apiCheckAlive)
  12. {
  13. Version = HttpVersion.Version20,
  14. VersionPolicy = HttpVersionPolicy.RequestVersionExact,
  15. };
  16. using var client = new HttpClient { BaseAddress = ServerUri };
  17. client.Timeout = TimeSpan.FromSeconds(timeoutInSecond);
  18. var httpResponse = await client.SendAsync(httpRequest);
  19. httpResponse.EnsureSuccessStatusCode();
  20. var rm = await httpResponse.Content.ReadAsStringAsync();
  21. return rm == aliveMessage;
  22. }
  23. catch
  24. {
  25. return false;
  26. }
  27. }
  28. }