get public ip

messaging
Tudor Stanciu 2019-10-28 23:53:39 +02:00
parent 873d743959
commit 08b12621b4
6 changed files with 80 additions and 8 deletions

View File

@ -1,8 +0,0 @@
using System;
namespace NDB.Infrastructure.PublicIP
{
public class Class1
{
}
}

View File

@ -0,0 +1,13 @@
using Microsoft.Extensions.DependencyInjection;
using NDB.Infrastructure.PublicIP.Services;
namespace NDB.Infrastructure.PublicIP
{
public static class DependencyInjectionExtensions
{
public static void AddPublicIPService(this IServiceCollection services)
{
services.AddHttpClient<IPublicIPService, PublicIPService>();
}
}
}

View File

@ -0,0 +1,7 @@
namespace NDB.Infrastructure.PublicIP.Entities
{
public class IPInfo
{
public string ip { get; set; }
}
}

View File

@ -4,4 +4,10 @@
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="3.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,10 @@
using NDB.Infrastructure.PublicIP.Entities;
using System.Threading.Tasks;
namespace NDB.Infrastructure.PublicIP.Services
{
public interface IPublicIPService
{
Task<IPInfo> GetPublicIP();
}
}

View File

@ -0,0 +1,44 @@
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<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());
}
}