45 lines
1.3 KiB
C#
45 lines
1.3 KiB
C#
using Netmash.Infrastructure.PublicIP.Entities;
|
|
using Newtonsoft.Json;
|
|
using System.Net.Http;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Netmash.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<IPInfo> 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<IPInfo> GetResult(HttpResponseMessage response) => JsonConvert.DeserializeObject<IPInfo>(await response.Content.ReadAsStringAsync());
|
|
}
|
|
}
|