欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 焦点 > C# Net 調用 MaxMind GeoLite2 資料庫

C# Net 調用 MaxMind GeoLite2 資料庫

2025/6/21 5:09:04 来源:https://blog.csdn.net/ytwoktwo/article/details/148688283  浏览:    关键词:C# Net 調用 MaxMind GeoLite2 資料庫

以下是如何下載並使用 MaxMind 的 GeoIP2 本地資料庫(以 GeoLite2-Country 資料庫為例)的詳細流程,以及如何在 .NET Core 8 中結合 MaxMind.GeoIP2 套件做 IP 判斷。


1. 下載 MaxMind GeoLite2 資料庫

MaxMind 提供免費的 GeoLite2 資料庫,需要先註冊帳號取得下載權限:

  1. 註冊或登入 MaxMind 官方網站

    • 網址:https://www.maxmind.com/en/geolite2/signup
  2. 完成註冊後,在「My Account」頁面找到「GeoLite2 Databases」區塊

  3. 下載「GeoLite2-Country」檔案(格式為 .mmdb

  4. 將下載的 .mmdb 檔案存放到你的專案資料夾(例如 App_Data 或專案根目錄)


2. 安裝 NuGet 套件

在你的 .NET Core 8 專案中,安裝 MaxMind 的官方套件:

bash 复制代码 

dotnet add package MaxMind.GeoIP2

或 Visual Studio 的 NuGet 管理器安裝 MaxMind.GeoIP2


3. 使用範例程式碼

以下展示一個簡單的使用範例,用來判斷給定 IP 是否來自澳門:

csharp 复制代码 

using MaxMind.GeoIP2;
using MaxMind.GeoIP2.Responses;
using System;public class IpChecker
{private readonly string _dbPath;public IpChecker(string dbPath){_dbPath = dbPath;}public bool IsIpFromMacau(string ip){try{using var reader = new DatabaseReader(_dbPath);CountryResponse response = reader.Country(ip);return response?.Country?.IsoCode?.Equals("MO", StringComparison.OrdinalIgnoreCase) == true;}catch (Exception ex){// 例外處理,例如 IP 格式不正確或資料庫文件有問題Console.WriteLine($"Error when checking IP: {ex.Message}");return false;}}
}

4. 使用範例

假設你將 GeoLite2-Country.mmdb 放在專案 App_Data 資料夾:

csharp 复制代码 

string dbPath = Path.Combine(AppContext.BaseDirectory, "App_Data", "GeoLite2-Country.mmdb");
var ipChecker = new IpChecker(dbPath);string testIp = "203.8.134.25"; // 替換成你想測試的 IPbool isFromMacau = ipChecker.IsIpFromMacau(testIp);
Console.WriteLine(isFromMacau ? "來自澳門" : "非澳門 IP");

注意事項

  • GeoLite2 資料庫會定期更新,建議定期下載最新版本
  • MaxMind 自 2019 年起需註冊並使用帳號授權下載資料庫,請務必先註冊,以免無法下載
  • 若你要在 ASP.NET Core 中使用,建議將判斷封裝成服務或中間件,並妥善處理併發和資料庫檔案載入問題

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com