public async Task <Countries> GetCountryCodeAsync(CancellationToken cancellationToken) { Countries result = Countries.UN; IpWhoisGeoData geoData = await GetDataAsync(cancellationToken); if (geoData != null) { if (Enum.TryParse(geoData.country_code, out Countries parseResult)) { result = parseResult; _log.LogInformation("Geodata received successfully, runtime country is {Country}", result.ToString()); } } return(result); }
private async Task <IpWhoisGeoData> GetDataAsync(CancellationToken cancellationToken) { IpWhoisGeoData result = null; try { HttpClient client = _httpClientFactory.CreateClient(); client.BaseAddress = new Uri(_providerUrl); string userAgent = $"{Program.AppName}/{Program.AppVersion}"; client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", userAgent); client.Timeout = TimeSpan.FromSeconds(60); HttpResponseMessage response = await client.GetAsync(new Uri("json/?lang=ru&objects=country_code", UriKind.Relative), cancellationToken); response.EnsureSuccessStatusCode(); using (Stream responseStream = await response.Content.ReadAsStreamAsync(cancellationToken)) { IpWhoisGeoData data = await JsonSerializer .DeserializeAsync <IpWhoisGeoData>(responseStream, new JsonSerializerOptions(), cancellationToken); if (data != null) { result = data; } else { _log.LogWarning("No geodata available."); } } } catch (TaskCanceledException ex) { _log.LogWarning("Unable to get runtime geodata: {ExceptionMessage}", ex.Message); } catch (Exception ex) { _log.LogError(ex, "Error getting geodata"); } return(result); }