using NDB.Infrastructure.PublicIP.Entities; using Newtonsoft.Json; using System.Net.Http; using System.Threading.Tasks; namespace NDB.Infrastructure.PublicIP.Services { public class PublicIPService : IPublicIPService { private const string _url1 = "https://api.ipify.org/?format=json"; private const string _url2 = "https://ip.seeip.org/json"; private readonly HttpClient _httpClient; public PublicIPService(HttpClient httpClient) { _httpClient = httpClient; } public async Task GetPublicIP() { IPInfo result = null; using (var response = await _httpClient.GetAsync(_url1)) { if (response.IsSuccessStatusCode) result = await GetResult(response); } if (result != null) return result; using (var response = await _httpClient.GetAsync(_url2)) { if (response.IsSuccessStatusCode) result = await GetResult(response); } return result; } private async Task GetResult(HttpResponseMessage response) => JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); } }