GeoIpServices 10.1.1
dotnet add package GeoIpServices --version 10.1.1
NuGet\Install-Package GeoIpServices -Version 10.1.1
<PackageReference Include="GeoIpServices" Version="10.1.1" />
<PackageVersion Include="GeoIpServices" Version="10.1.1" />
<PackageReference Include="GeoIpServices" />
paket add GeoIpServices --version 10.1.1
#r "nuget: GeoIpServices, 10.1.1"
#:package GeoIpServices@10.1.1
#addin nuget:?package=GeoIpServices&version=10.1.1
#tool nuget:?package=GeoIpServices&version=10.1.1
GeoIpServices
GeoIpServices is an open-source C# library that provides geolocation information for IP addresses with intelligent MongoDB caching. It wraps third-party IP geolocation services (currently supporting IpStack) to significantly reduce API usage and costs through smart caching and session management.
✨ Features
- 🌍 IP Geolocation Lookup - Convert IPv4 addresses to geographic information (country, region, city, etc.)
- 💾 MongoDB Caching - Store geolocation data in your own MongoDB instance with automatic TTL-based expiration
- 🔄 Round-Robin Fallback - Automatic retry mechanism with configurable priority-based provider queuing
- 📊 Session Management - Track lookup sessions to prevent duplicate queries and manage retries efficiently
- 🔌 Extensible Architecture - Easy to add support for additional IP geolocation providers
- ⚡ Cost Effective - Dramatically reduce API costs for high-traffic applications through intelligent caching
📋 Prerequisites
- .NET 10.0 or later
- MongoDB instance (local or cloud-based like MongoDB Atlas)
- IpStack API key (get one at ipstack.com)
- MongoDbService package (automatically installed as dependency)
🚀 Getting Started
Installation
Install the NuGet package using the .NET CLI:
dotnet add package GeoIpServices
Or via Package Manager Console:
Install-Package GeoIpServices
Configuration
Add the following configuration to your appsettings.json:
{
"MongoDbSettings": {
"ConnectionString": "mongodb://localhost:27017",
"DatabaseName": "GeoIpDatabase"
},
"GeoIpSettings": {
"Controls": {
"SessionTimeoutInSeconds": 300,
"CacheDurationInHours": 24,
"MaxRoundRobinAttempts": 2,
"Priority": [ "IpStack" ]
},
"IpStack": {
"ApiPrefix": "https://api.ipstack.com/",
"ApiPostfix": "?access_key=YOUR_IPSTACK_API_KEY_HERE"
}
}
}
Configuration Options:
| Option | Default | Description |
|---|---|---|
SessionTimeoutInSeconds |
300 | How long lookup sessions remain active before expiring (MongoDB TTL) |
CacheDurationInHours |
24 | How long cached geolocation data is retained before expiring (MongoDB TTL) |
MaxRoundRobinAttempts |
1 | Number of retry cycles through all providers |
Priority |
Required | Array of providers to use in order of preference (e.g., ["IpStack"]) |
ApiPostfix |
Required | Your IpStack API key - Important: Keep this in user secrets or environment variables in production! |
Note: Both
SessionTimeoutInSecondsandCacheDurationInHoursuse MongoDB TTL indexes for automatic cleanup of expired documents.
Usage Example
Here's a complete example of a minimal API that returns geolocation information for the requesting IP:
using GeoIpServices;
using Microsoft.AspNetCore.Mvc;
using MongoDbService;
using System.Net;
using System.Net.Sockets;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Register MongoDB and GeoIp services
builder.Services.AddMongoDbServices();
builder.Services.AddGeoIpServices();
var app = builder.Build();
// Configure the HTTP request pipeline
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
// Endpoint to get geolocation info from visitor's IP
// You can inject either IGeoInfoService (interface) or GeoIpService (concrete class)
app.MapGet("/ipinfo", async ([FromServices] GeoIpService geoIpService, HttpRequest httpRequest) =>
{
var ipAddress = GetOriginIpV4(httpRequest);
if (ipAddress is null)
{
return Results.BadRequest("Unable to determine IP address");
}
var geoInfo = await geoIpService.GetGeoIpInfoFromIpv4(ipAddress);
if (geoInfo is null)
{
return Results.NotFound("Geolocation information not available");
}
return Results.Ok(geoInfo);
})
.WithName("GetGeoIpInfoFromIpv4")
.WithOpenApi();
// Helper method to extract client IP from request
IPAddress? GetOriginIpV4(HttpRequest httpRequest)
{
var xForwardedForHeader = httpRequest.Headers["X-Forwarded-For"];
var ipString = xForwardedForHeader.Select(s => s?.Trim()).FirstOrDefault();
if (string.IsNullOrWhiteSpace(ipString) || !IPAddress.TryParse(ipString, out IPAddress? clientIpAddress))
{
return null;
}
if (clientIpAddress.AddressFamily == AddressFamily.InterNetworkV6)
{
return clientIpAddress.MapToIPv4();
}
return clientIpAddress;
}
app.Run();
🔧 Troubleshooting
Common Issues
Issue: "Unable to fetch info for IP"
- Verify your IpStack API key is correct in
appsettings.json - Check that you haven't exceeded your IpStack API quota
- Ensure your MongoDB connection string is valid and the database is accessible
Issue: MongoDB connection errors
- Verify MongoDB is running and accessible at the specified connection string
- Check firewall rules if using a remote MongoDB instance
- Ensure the database user has read/write permissions
Issue: Always getting fresh data (cache not working)
- Check
CacheDurationInHoursis set appropriately - Verify MongoDB TTL indexes are created on the collections
- Check application logs for any database write errors
Issue: Configuration errors on startup
- Ensure all required configuration values are present (
Priority,ApiPrefix,ApiPostfix) - Verify
ApiPostfixstarts with?access_key= - Check that
Prioritycontains at least one valid provider name
🤝 Contributing
We welcome contributions! If you find a bug or have an idea for improvement:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📝 License
This project is licensed under the GNU General Public License v3.0. See the LICENSE file for details.
🔗 Links
🙏 Acknowledgments
- Built with MongoDbService
- Powered by IpStack API
Happy coding! 🚀🌐📚
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- EarthCountriesInfo (>= 10.0.0)
- HumanLanguages (>= 10.2.0)
- Microsoft.Extensions.Configuration.Abstractions (>= 10.0.0)
- Microsoft.Extensions.Configuration.Binder (>= 10.0.0)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 10.0.0)
- Microsoft.Extensions.Http (>= 10.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 10.0.0)
- MongoDB.Bson (>= 3.5.1)
- MongoDB.Driver (>= 3.5.1)
- MongoDbService (>= 10.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 10.1.1 | 185 | 12/14/2025 |
| 10.1.0 | 165 | 12/14/2025 |
| 10.0.0 | 242 | 11/26/2025 |
| 6.0.1 | 1,012 | 7/27/2025 |
| 6.0.0 | 959 | 6/28/2025 |
| 5.0.0 | 1,226 | 1/8/2025 |
| 4.0.0 | 1,031 | 8/11/2024 |
| 3.1.0 | 1,024 | 7/8/2024 |
| 3.0.0 | 958 | 7/8/2024 |
| 2.0.5 | 967 | 7/8/2024 |
| 2.0.4 | 970 | 7/7/2024 |
| 2.0.3 | 953 | 7/7/2024 |
| 2.0.0 | 955 | 7/7/2024 |
| 1.0.0 | 954 | 7/7/2024 |