GeoIpServices 10.1.1

dotnet add package GeoIpServices --version 10.1.1
                    
NuGet\Install-Package GeoIpServices -Version 10.1.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="GeoIpServices" Version="10.1.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="GeoIpServices" Version="10.1.1" />
                    
Directory.Packages.props
<PackageReference Include="GeoIpServices" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add GeoIpServices --version 10.1.1
                    
#r "nuget: GeoIpServices, 10.1.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package GeoIpServices@10.1.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=GeoIpServices&version=10.1.1
                    
Install as a Cake Addin
#tool nuget:?package=GeoIpServices&version=10.1.1
                    
Install as a Cake Tool

GeoIpServices

NuGet NuGet Downloads License

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 SessionTimeoutInSeconds and CacheDurationInHours use 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 CacheDurationInHours is 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 ApiPostfix starts with ?access_key=
  • Check that Priority contains at least one valid provider name

🤝 Contributing

We welcome contributions! If you find a bug or have an idea for improvement:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📝 License

This project is licensed under the GNU General Public License v3.0. See the LICENSE file for details.

🙏 Acknowledgments


Happy coding! 🚀🌐📚

Product 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

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