📅  最后修改于: 2022-03-11 14:48:59.231000             🧑  作者: Mango
// 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";
}
Hey there, welcome visitor from @Model.City, @Model.Country!
Your time zone is @Model.Location.TimeZone
// 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?}");
});
}
}