从 ASP.net MVC 中的 IP 地址获取国家/地区的安全方法

safe way to get the country from an IP Address in ASP.net MVC

我在多语言网站上工作,我可以获得用户的 IP 地址,问题是我正在寻找一种非常安全和值得信赖的方式来获取 IP 并给我国家代码,我希望用户面对他们自己的进入我的网站时的语言页面,我以前使用过一次,但它停止提供服务。有没有人知道如何去做?这是我的代码,非常感谢您的帮助。我正在寻找一个真正值得信赖的 google 或其他 API 甚至任何代码建议

    public async Task<ActionResult> Index()
    {


        try
        {
            string userIpAddress = this.Request.UserHostAddress;
            var client = new HttpClient
            {
                BaseAddress = new Uri("https:// `I need API HERE` ")
            };

            var response = await client.GetAsync(userIpAddress);

            var content = await response.Content.ReadAsStringAsync();

            var result = (Response)new XmlSerializer(typeof(Response)).Deserialize(new StringReader(content));
            var country_name = result.CountryName;
            var country_code = result.CountryCode;
            TempData["Country_code"] = country_code;
            TempData["Country_name"] = country_name;

            if (country_code == "FR")
            {
                return RedirectToAction("fr", "Home");
            }
            else if (country_code == "JP")
            {
                return RedirectToAction("jp", "Home");
            }
            else if (country_code == "DE")
            {
                return RedirectToAction("de", "Home");
            }

            else if (country_code == "NL")
            {
                return RedirectToAction("nl", "Home");
            }
            else if (country_code == "CN")
            {
                return RedirectToAction("cn", "Home");
            }
            else if (country_code == "DK")
            {
                return RedirectToAction("dk", "Home");
            }
            else if (country_code == "RU")
            {
                return RedirectToAction("ru", "Home");
            }
            else
            {
                return RedirectToAction("en", "Home");

            }


        }
        catch
        {
            return RedirectToAction("en", "Home");
        }


    }

不要为此使用 IP 地址。这不是解决问题的好方法。例如,如果英国用户在度假时随身携带笔记本电脑,并在其他国家/地区使用您的网站怎么办?他们可能仍想以英语查看网站,但您最终将以不同的语言向他们提供内容。

而是使用 Accept-Language 请求 HTTP header:

This header is a hint to be used when the server has no way of determining the language via another way, like a specific URL, that is controlled by an explicit user decision.

一个例子

StringWithQualityHeaderValue preferredLanguage = null;
if (Request.Headers.AllKeys.Contains("Accept-Language"))
{
    preferredLanguage = Request.Headers["Accept-Language"]
        .Split(',')
        .Select(StringWithQualityHeaderValue.Parse)
        .OrderByDescending(s => s.Quality.GetValueOrDefault(1))
        .FirstOrDefault();
}

if (preferredLanguage?.Value == "fr")
{
    return RedirectToAction("fr", "home");
}
// Check for other languages.    
// ...
// If no redirects match, default to English.
return RedirectToAction("en", "home");