In this article, we are going to fetch user public IP Addresses and Geolocation in the blazor webassembly application.
Now implement logic to fetch the IP Address API by creating a service file.
Third-Party APIs:
The API to get users IP Address endpoint:
https://jsonip.com/
Free endpoint, for official docs, visit "https://getjsonip.com/#docs".
https://jsonip.com/
Free endpoint, for official docs, visit "https://getjsonip.com/#docs".
The API to get users Geolocation based on users IP Address endpoint:
http://api.ipstack.com/User_IP?access_key=your_api_key&format=1
This endpoint has pricing subscription plans including the free subscription plan, for official docs, visit: "https://ipstack.com/"
Create A Sample Blazor WebAssembly:
Let's begin our demo by creating a sample Blazor WebAssembly application. For development, any type of IDE can be used but more recommended are Visual Studio 2019(Version 16.8.* latest that builds .Net5) or Visual Studio Code.
Fetch User IP Address:
Now let's create a model that represents the IP Address payload.
Models/IPAddress.cs:
using System.Text.Json.Serialization; namespace Blwasm.IPGeolocation.Models { public class IPAddress { [JsonPropertyName("ip")] public string IP{get;set;} [JsonPropertyName("geo-ip")] public string GeoIP{get;set;} [JsonPropertyName("API Help")] public string APIHelp{get;set;} } }
- The 'JsonPropertyName' attribute to map the payload parameters to c# class properties. This 'JsonPropertyName' attribute loads from the 'System.Text.Json.Serialization'
Package Manager
Install-Package Microsoft.Extensions.Http -Version 5.0.0
.Net CLI
dotnet add package Microsoft.Extensions.Http --version 5.0.0
Register HttpClient with IP Address base domain using named HTTP client technique.Program.cs:
builder.Services.AddHttpClient("IP",(options) => { options.BaseAddress = new Uri("https://jsonip.com"); });
- Here we register HTTP Client with the name "IP". This name should be used for creating an HTTP client object from the HttpClientFactory.
Services/IApiClietService.cs:
using System.Threading.Tasks; using Blwasm.IPGeolocation.Models; namespace Blwasm.IPGeolocation.Services { public interface IApiClientService { Task<IPAddress> GetUserIPAsync(); } }Services/ApiClientService.cs:
using System.Net.Http; using System.Net.Http.Json; using System.Threading.Tasks; using Blwasm.IPGeolocation.Models; namespace Blwasm.IPGeolocation.Services { public class ApiClientService: IApiClientService { private readonly IHttpClientFactory _httpClientFactory; public ApiClientService(IHttpClientFactory httpClientfactory) { _httpClientFactory = httpClientfactory; } public async Task<IPAddress> GetUserIPAsync() { var client = _httpClientFactory.CreateClient("IP"); return await client.GetFromJsonAsync<IPAddress>("/"); } } }
- (Line: 12) Injected the HttpClientFacotry.
- (Line: 19) Creating an HTTP Client object from the HttpClientFacotry by inputting the name "IP".
- (Line: 20) Invoking the API and converting the response to 'IPAddress' type with the help of an extension method like 'GetFromJsonAsync<>' that loads from System.Net.Http.Json. Here we passed the "/" as a path because domain itself returning the IP Address results.
Program.cs:
builder.Services.AddScoped<IApiClientService,ApiClientService>();Now update the Index.razor page to display the user's IP Address.
Pages/Index.razor:(Html Part)
@page "/" @inject IApiClientService _apiClientService; <div> <h4>User Ip - @ipAddress.IP</h4> </div>
- Here using razor syntax injecting the 'IApiClientService'
@code{ IPAddress ipAddress = new IPAddress(); protected override async Task OnInitializedAsync() { ipAddress = await _apiClientService.GetUserIPAsync(); } }
- Inside of the lifecycle method like 'OnInitializedAsyn()' invoking the IP Address API call.
Fetch User's Geolocation:
Now let's create a payload model for the Geolocation API(HTTP://api.ipstack.com)
Models/UserGeolocation.cs:
using System; using System.Collections.Generic; namespace Blwasm.IPGeolocation.Models { public class Language { public string code { get; set; } public string name { get; set; } public string native { get; set; } } public class Location { public int? geoname_id { get; set; } public string capital { get; set; } public List<Language> languages { get; set; } public string country_flag { get; set; } public string country_flag_emoji { get; set; } public string country_flag_emoji_unicode { get; set; } public string calling_code { get; set; } public bool? is_eu { get; set; } } public class TimeZone { public string id { get; set; } public DateTime current_time { get; set; } public int? gmt_offset { get; set; } public string code { get; set; } public bool is_daylight_saving { get; set; } } public class Currency { public string code { get; set; } public string name { get; set; } public string plural { get; set; } public string symbol { get; set; } public string symbol_native { get; set; } } public class Connection { public int? asn { get; set; } public string isp { get; set; } } public class Security { public bool is_proxy { get; set; } public object proxy_type { get; set; } public bool is_crawler { get; set; } public object crawler_name { get; set; } public object crawler_type { get; set; } public bool is_tor { get; set; } public string threat_level { get; set; } public object threat_types { get; set; } } public class UserGeoLocation { public string ip { get; set; } public string hostname { get; set; } public string type { get; set; } public string continent_code { get; set; } public string continent_name { get; set; } public string country_code { get; set; } public string country_name { get; set; } public string region_code { get; set; } public string region_name { get; set; } public string city { get; set; } public string zip { get; set; } public double? latitude { get; set; } public double? longitude { get; set; } public Location location { get; set; } public TimeZone time_zone { get; set; } public Currency currency { get; set; } public Connection connection { get; set; } public Security security { get; set; } } }Now register the HTTP client for the geolocation API
Program.cs:
builder.Services.AddHttpClient("Location", options => { options.BaseAddress = new Uri("http://api.ipstack.com"); });
- Registered the geolocation API with the name 'Location'.
Services/IApiClientService.cs:
Task<UserGeoLocation> GetLocationAsync(string userIp);Services/ApiClientService.cs:
public async Task<UserGeoLocation> GetLocationAsync(string userIp) { string path = $"{userIp}?access_key=Your_Secured_Key"; var client = _httpClientFactory.CreateClient("Location"); return await client.GetFromJsonAsync<UserGeoLocation>(path); }
- Here URL is made of the User Ip address and API secured key that's will get once registered with "HTTP://ipstack.com".
- Creating the HTTP client object by using the name "Location" from the HttpClientFactory.
Pages/Index.razor:(Html Part)
<div> <h4>User Ip - @ipAddress.IP</h4> <ul> <li>Country - @location.country_name</li> <li>Regionname - @location.region_name</li> <li>City - @location.city</li> </ul> </div>Pages/Index.razor:(Code Part)
@code{ IPAddress ipAddress = new IPAddress(); UserGeoLocation location = new UserGeoLocation(); protected override async Task OnInitializedAsync() { ipAddress = await _apiClientService.GetUserIPAsync(); location = await _apiClientService.GetLocationAsync(ipAddress.IP); } }That's all about the fetching User IP Address and Geolocation in the blazor webassembly application.
Support Me!
Buy Me A Coffee
PayPal Me
Wrapping Up:
Hopefully, I think this article delivered some useful information about fetching user IP Addresses and Geolocation in the Blazor Application. I love to have your feedback, suggestions, and better techniques in the comment section below.
Comments
Post a Comment