0

My workteam created a MVC Application integrated with an API for school project. This API is connected to n APIs.

I want to do HttpGet from the "main" API which will ask all APIs to make HttpGet in order to obtain lists from each one of them. I want this to work even if some APIs are offline but ... How can I check their internet connection through their Uri before making those Http requests? I tried to ping the API but I found some problems

public async Task<List<Booking>> GetAvailable(DateTime start, DateTime end)
{
        var uriList = new List<string>();
        var availableList = new List<Booking>();
        var hotelList = await _repo.FindAllAsync();
        
        foreach (var hotel in hotelList)
        {
            uriList.Add(hotel.Uri);
        }
        foreach (var uri in uriList)
            {
                if(ServerConnected(uri))
                {
                    using (var client = new HttpClient())
                    { 
                        client.BaseAddress = new Uri(uri);
                        client.DefaultRequestHeaders.Accept.Clear();
                        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                        (...)
}
                
(...)

public static bool ServerConnected(string url)
     {
        Ping pingSender = new Ping();
        var reply = pingSender.Send(url);

        if (reply.Status == IPStatus.Success)
        {
            return true;
        }
        else
            return false;
    }
  • The API's that you want to check are up or down - do you control them? If you don't the best you can hope for is that the developer was kind enough to integrate a healthcheck endpoint. Otherwise you might be stuck making a dummy call to the site and verifying it succeeds. If you control the APIs, consider adding health checks to your app – mason Mar 03 '21 at 18:50
  • _"I tried to ping the API but I found some problems"_ -- "found some problems" is not a useful problem description. More generally though, while one can _sometimes_ use ping to determine server availability, _there is no point in doing so_. A nanosecond after you find that the server is available, it could become unavailable. The only reasonable thing to do is to only try to connect to the server when you need it, and don't worry about whether it's available any other time. – Peter Duniho Mar 03 '21 at 19:46

0 Answers0