Обнаружение местоположения с IP -адреса .NET CORE
// Install-Package MaxMind.GeoIP2
// controller
public class HomeController : Controller
{
private readonly IHostingEnvironment _hostingEnvironment;
public HomeController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
public IActionResult Index()
{
using (var reader = new DatabaseReader(_hostingEnvironment.ContentRootPath + "\\GeoLite2-City.mmdb"))
{
// Determine the IP Address of the request
var ipAddress = HttpContext.Connection.RemoteIpAddress;
// Get the city from the IP Address
var city = reader.City(ipAddress);
return View(city);
}
}
}
// razor
@model MaxMind.GeoIP2.Responses.CityResponse
@{
ViewData["Title"] = "Home Page";
}
<div class="row" style="margin-top: 50px;">
<div class="col-md-12">
<p>Hey there, welcome visitor from <strong>@Model.City, @Model.Country!</strong></p>
<p>Your time zone is <strong>@Model.Location.TimeZone</strong></p>
</div>
</div>
// startup or now program file
public class Startup
{
// Some code omitted from this code sample for brevity...
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor,
// IIS is also tagging a X-Forwarded-For header on, so we need to increase this limit,
// otherwise the X-Forwarded-For we are passing along from the browser will be ignored
ForwardLimit = 2
});
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
code fighter