Esta distribución proporciona una API para las bases de datos y servicios web GeoIP2 y GeoLite2.
Recomendamos instalar esta biblioteca con NuGet. Para hacer esto, escriba lo siguiente en la consola del Administrador de paquetes de Visual Studio:
install-package MaxMind.GeoIP2
La geolocalización de IP es inherentemente imprecisa. Las ubicaciones suelen estar cerca del centro de la población. Cualquier ubicación proporcionada por una base de datos o servicio web GeoIP2 no debe usarse para identificar una dirección o un hogar en particular.
Para utilizar la API del servicio web, primero cree un nuevo objeto WebServiceClient
con su ID de cuenta y clave de licencia:
var client = new WebServiceClient(42, "license_key1");
Para consultar el servicio web GeoLite2, debe configurar el host en geolite.info
:
var client = new WebServiceClient(42, "license_key1", host: "geolite.info");
Para consultar el servicio web Sandbox GeoIP2, debe configurar el host en sandbox.maxmind.com
:
var client = new WebServiceClient(42, "license_key1", host: "sandbox.maxmind.com");
También puede especificar las configuraciones regionales alternativas, el host o el tiempo de espera como parámetros opcionales. Consulte los documentos de API para obtener más información.
Este objeto es seguro para compartir entre subprocesos. Si realiza varias solicitudes, el objeto debe reutilizarse para que no se creen nuevas conexiones para cada solicitud. Una vez que haya terminado de realizar solicitudes, debe deshacerse del objeto para asegurarse de que las conexiones estén cerradas y que los recursos se devuelvan rápidamente al sistema.
Luego puede llamar al método sync o async correspondiente al punto final específico, pasándole la dirección IP que desea buscar o ningún parámetro si desea buscar el dispositivo actual.
Si la solicitud tiene éxito, la llamada al método devolverá una clase de respuesta para el punto final al que llamó. Esta respuesta, a su vez, contiene múltiples clases de modelo, cada una de las cuales representa parte de los datos devueltos por el servicio web.
Consulte la documentación de la API para obtener más detalles.
Para utilizar la API del servicio web con el patrón de fábrica HttpClient como cliente con tipo, debe hacer lo siguiente:
ConfigureServices
Startup.cs
: // Configure to read configuration options from MaxMind section
services . Configure < WebServiceClientOptions > ( Configuration . GetSection ( " MaxMind " ) ) ;
// Configure dependency injection for WebServiceClient
services . AddHttpClient < WebServiceClient > ( ) ;
appsettings.json
con su ID de cuenta y clave de licencia. ...
"MaxMind" : {
"AccountId" : 123456 ,
"LicenseKey" : "1234567890" ,
// Optionally set a timeout. The default is 3000 ms.
// "Timeout": 3000,
// Optionally set host. "geolite.info" will use the GeoLite2
// web service instead of GeoIP2. "sandbox.maxmind.com" will use the
// Sandbox GeoIP2 web service instead of the production GeoIP2 web
// service.
//
// "Host": "geolite.info"
} ,
...
WebServiceClient
donde necesita realizar la llamada y úselo. [ ApiController ]
[ Route ( " [controller] " ) ]
public class MaxMindController : ControllerBase
{
private readonly WebServiceClient _maxMindClient ;
public MaxMindController ( WebServiceClient maxMindClient )
{
_maxMindClient = maxMindClient ;
}
[ HttpGet ]
public async Task < string > Get ( )
{
var location = await _maxMindClient . CountryAsync ( ) ;
return location . Country . Name ;
}
}
// If you are making multiple requests, a single WebServiceClient
// should be shared across requests to allow connection reuse. The
// class is thread safe.
//
// Replace "42" with your account ID and "license_key" with your license
// key. Set the named host argument to "geolite.info" to use the GeoLite2
// web service instead of GeoIP2. Set the named host argument to
// "sandbox.maxmind.com" to use the Sandbox GeoIP2 web service instead of
// the production GeoIP2 web service.
using ( var client = new WebServiceClient ( 42 , " license_key " ) )
{
// Do the lookup
var response = client . Country ( " 128.101.101.101 " ) ;
Console . WriteLine ( response . Country . IsoCode ) ; // 'US'
Console . WriteLine ( response . Country . Name ) ; // 'United States'
Console . WriteLine ( response . Country . Names [ " zh-CN " ] ) ; // '美国'
}
// If you are making multiple requests, a single WebServiceClient
// should be shared across requests to allow connection reuse. The
// class is thread safe.
//
// Replace "42" with your account ID and "license_key" with your license
// key. Set the named host argument to "geolite.info" to use the GeoLite2
// web service instead of GeoIP2. Set the named host argument to
// "sandbox.maxmind.com" to use the Sandbox GeoIP2 web service instead of
// the production GeoIP2 web service.
using ( var client = new WebServiceClient ( 42 , " license_key " ) )
{
// Do the lookup
var response = await client . CountryAsync ( " 128.101.101.101 " ) ;
Console . WriteLine ( response . Country . IsoCode ) ; // 'US'
Console . WriteLine ( response . Country . Name ) ; // 'United States'
Console . WriteLine ( response . Country . Names [ " zh-CN " ] ) ; // '美国'
}
// If you are making multiple requests, a single WebServiceClient
// should be shared across requests to allow connection reuse. The
// class is thread safe.
//
// Replace "42" with your account ID and "license_key" with your license
// key. Set the named host argument to "geolite.info" to use the GeoLite2
// web service instead of GeoIP2. Set the named host argument to
// "sandbox.maxmind.com" to use the Sandbox GeoIP2 web service instead of
// the production GeoIP2 web service.
using ( var client = new WebServiceClient ( 42 , " license_key " ) )
{
// Do the lookup
var response = client . City ( " 128.101.101.101 " ) ;
Console . WriteLine ( response . Country . IsoCode ) ; // 'US'
Console . WriteLine ( response . Country . Name ) ; // 'United States'
Console . WriteLine ( response . Country . Names [ " zh-CN " ] ) ; // '美国'
Console . WriteLine ( response . MostSpecificSubdivision . Name ) ; // 'Minnesota'
Console . WriteLine ( response . MostSpecificSubdivision . IsoCode ) ; // 'MN'
Console . WriteLine ( response . City . Name ) ; // 'Minneapolis'
Console . WriteLine ( response . Postal . Code ) ; // '55455'
Console . WriteLine ( response . Location . Latitude ) ; // 44.9733
Console . WriteLine ( response . Location . Longitude ) ; // -93.2323
}
// If you are making multiple requests, a single WebServiceClient
// should be shared across requests to allow connection reuse. The
// class is thread safe.
//
// Replace "42" with your account ID and "license_key" with your license
// key. Set the named host argument to "geolite.info" to use the GeoLite2
// web service instead of GeoIP2. Set the named host argument to
// "sandbox.maxmind.com" to use the Sandbox GeoIP2 web service instead of
// the production GeoIP2 web service.
using ( var client = new WebServiceClient ( 42 , " license_key " ) )
{
// Do the lookup
var response = await client . CityAsync ( " 128.101.101.101 " ) ;
Console . WriteLine ( response . Country . IsoCode ) ; // 'US'
Console . WriteLine ( response . Country . Name ) ; // 'United States'
Console . WriteLine ( response . Country . Names [ " zh-CN " ] ) ; // '美国'
Console . WriteLine ( response . MostSpecificSubdivision . Name ) ; // 'Minnesota'
Console . WriteLine ( response . MostSpecificSubdivision . IsoCode ) ; // 'MN'
Console . WriteLine ( response . City . Name ) ; // 'Minneapolis'
Console . WriteLine ( response . Postal . Code ) ; // '55455'
Console . WriteLine ( response . Location . Latitude ) ; // 44.9733
Console . WriteLine ( response . Location . Longitude ) ; // -93.2323
}
// If you are making multiple requests, a single WebServiceClient
// should be shared across requests to allow connection reuse. The
// class is thread safe.
//
// Replace "42" with your account ID and "license_key" with your license
// key. The GeoLite2 web service does not support Insights. Set the named
// host argument to "sandbox.maxmind.com" to use the Sandbox GeoIP2 web
// service instead of the production GeoIP2 web service.
using ( var client = new WebServiceClient ( 42 , " license_key " ) )
{
// Do the lookup
var response = client . Insights ( " 128.101.101.101 " ) ;
Console . WriteLine ( response . Country . IsoCode ) ; // 'US'
Console . WriteLine ( response . Country . Name ) ; // 'United States'
Console . WriteLine ( response . Country . Names [ " zh-CN " ] ) ; // '美国'
Console . WriteLine ( response . MostSpecificSubdivision . Name ) ; // 'Minnesota'
Console . WriteLine ( response . MostSpecificSubdivision . IsoCode ) ; // 'MN'
Console . WriteLine ( response . City . Name ) ; // 'Minneapolis'
Console . WriteLine ( response . Postal . Code ) ; // '55455'
Console . WriteLine ( response . Location . Latitude ) ; // 44.9733
Console . WriteLine ( response . Location . Longitude ) ; // -93.2323
}
// If you are making multiple requests, a single WebServiceClient
// should be shared across requests to allow connection reuse. The
// class is thread safe.
//
// Replace "42" with your account ID and "license_key" with your license
// key. The GeoLite2 web service does not support Insights. Set the named
// host argument to "sandbox.maxmind.com" to use the Sandbox GeoIP2 web
// service instead of the production GeoIP2 web service.
using ( var client = new WebServiceClient ( 42 , " license_key " ) )
{
// Do the lookup
var response = await client . InsightsAsync ( " 128.101.101.101 " ) ;
Console . WriteLine ( response . Country . IsoCode ) ; // 'US'
Console . WriteLine ( response . Country . Name ) ; // 'United States'
Console . WriteLine ( response . Country . Names [ " zh-CN " ] ) ; // '美国'
Console . WriteLine ( response . MostSpecificSubdivision . Name ) ; // 'Minnesota'
Console . WriteLine ( response . MostSpecificSubdivision . IsoCode ) ; // 'MN'
Console . WriteLine ( response . City . Name ) ; // 'Minneapolis'
Console . WriteLine ( response . Postal . Code ) ; // '55455'
Console . WriteLine ( response . Location . Latitude ) ; // 44.9733
Console . WriteLine ( response . Location . Longitude ) ; // -93.2323
}
Para utilizar la API de la base de datos, debe crear un nuevo DatabaseReader
con una representación de cadena de la ruta a su base de datos GeoIP2. También puede especificar el modo de acceso al archivo. Luego puede llamar al método apropiado (por ejemplo, city
) para su base de datos y pasarle la dirección IP que desea buscar.
Si la búsqueda tiene éxito, la llamada al método devolverá una clase de respuesta para la búsqueda GeoIP2. Esta clase, a su vez, contiene varias clases de modelo, cada una de las cuales representa parte de los datos devueltos por la base de datos.
Recomendamos reutilizar el objeto DatabaseReader
en lugar de crear uno nuevo para cada búsqueda. La creación de este objeto es relativamente costosa ya que debe leer los metadatos del archivo.
Consulte la documentación de la API para obtener más detalles.
using ( var reader = new DatabaseReader ( " GeoIP2-Anonymous-IP.mmdb " ) )
{
var response = reader . AnonymousIP ( " 85.25.43.84 " ) ;
Console . WriteLine ( response . IsAnonymous ) ; // true
Console . WriteLine ( response . IsAnonymousVpn ) ; // false
Console . WriteLine ( response . IsHostingProvider ) ; // false
Console . WriteLine ( response . IsPublicProxy ) ; // false
Console . WriteLine ( response . IsResidentialProxy ) ; // false
Console . WriteLine ( response . IsTorExitNode ) ; // true
Console . WriteLine ( response . IPAddress ) ; // '85.25.43.84'
}
using ( var reader = new DatabaseReader ( " GeoLite2-ASN.mmdb " ) )
{
var response = reader . Asn ( " 85.25.43.84 " ) ;
Console . WriteLine ( response . AutonomousSystemNumber ) ; // 217
Console . WriteLine ( response . AutonomousSystemOrganization ) ; // 'University of Minnesota'
Console . WriteLine ( response . IPAddress ) ; // '128.101.101.101'
}
// This creates the DatabaseReader object, which should be reused across
// lookups.
using ( var reader = new DatabaseReader ( " GeoIP2-City.mmdb " ) )
{
// Replace "City" with the appropriate method for your database, e.g.,
// "Country".
var city = reader . City ( " 128.101.101.101 " ) ;
Console . WriteLine ( city . Country . IsoCode ) ; // 'US'
Console . WriteLine ( city . Country . Name ) ; // 'United States'
Console . WriteLine ( city . Country . Names [ " zh-CN " ] ) ; // '美国'
Console . WriteLine ( city . MostSpecificSubdivision . Name ) ; // 'Minnesota'
Console . WriteLine ( city . MostSpecificSubdivision . IsoCode ) ; // 'MN'
Console . WriteLine ( city . City . Name ) ; // 'Minneapolis'
Console . WriteLine ( city . Postal . Code ) ; // '55455'
Console . WriteLine ( city . Location . Latitude ) ; // 44.9733
Console . WriteLine ( city . Location . Longitude ) ; // -93.2323
}
using ( var reader = new DatabaseReader ( " GeoIP2-Connection-Type.mmdb " ) )
{
var response = reader . ConnectionType ( " 128.101.101.101 " ) ;
Console . WriteLine ( response . ConnectionType ) ; // 'Corporate'
Console . WriteLine ( response . IPAddress ) ; // '128.101.101.101'
}
using ( var reader = new DatabaseReader ( " GeoIP2-Domain.mmdb " ) )
{
var response = reader . Domain ( " 128.101.101.101 " ) ;
Console . WriteLine ( response . Domain ) ; // 'umn.edu'
Console . WriteLine ( response . IPAddress ) ; // '128.101.101.101'
}
using ( var reader = new DatabaseReader ( " /path/to/GeoIP2-Enterprise.mmdb " ) )
{
// Use the Enterprise(ip) method to do a lookup in the Enterprise database
var response = reader . enterprise ( " 128.101.101.101 " ) ;
var country = response . Country ;
Console . WriteLine ( country . IsoCode ) ; // 'US'
Console . WriteLine ( country . Name ) ; // 'United States'
Console . WriteLine ( country . Names [ " zh-CN " ] ) ; // '美国'
Console . WriteLine ( country . Confidence ) ; // 99
var subdivision = response . MostSpecificSubdivision ;
Console . WriteLine ( subdivision . Name ) ; // 'Minnesota'
Console . WriteLine ( subdivision . IsoCode ) ; // 'MN'
Console . WriteLine ( subdivision . Confidence ) ; // 77
var city = response . City ;
Console . WriteLine ( city . Name ) ; // 'Minneapolis'
Console . WriteLine ( city . Confidence ) ; // 11
var postal = response . Postal ;
Console . WriteLine ( postal . Code ) ; // '55455'
Console . WriteLine ( postal . Confidence ) ; // 5
var location = response . Location ;
Console . WriteLine ( location . Latitude ) ; // 44.9733
Console . WriteLine ( location . Longitude ) ; // -93.2323
Console . WriteLine ( location . AccuracyRadius ) ; // 50
}
using ( var reader = new DatabaseReader ( " GeoIP2-ISP.mmdb " ) )
{
var response = reader . Isp ( " 128.101.101.101 " ) ;
Console . WriteLine ( response . AutonomousSystemNumber ) ; // 217
Console . WriteLine ( response . AutonomousSystemOrganization ) ; // 'University of Minnesota'
Console . WriteLine ( response . Isp ) ; // 'University of Minnesota'
Console . WriteLine ( response . Organization