我正在多语言网站上工作,我可以获取用户的IP地址,问题是我正在寻找一种非常安全且可信赖的方式来获取IP并提供国家代码,我希望用户面对自己的语言页面进入我的网站时,我曾经使用过一次,但是它停止提供服务。有谁知道如何做吗?这是我的代码,非常感谢您的帮助。我正在寻找一种真正值得信赖的工具,谷歌或其他一些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");
}
}
答案 0 :(得分:1)
请勿为此使用IP地址。这不是解决该问题的好方法。例如,如果英语用户带着他们的笔记本电脑去度假,并使用其他国家的网站怎么办?他们可能仍然想用英语查看该网站,但是您最终将以另一种语言向他们提供内容。
相反,请使用Accept-Language请求的HTTP标头:
此标头是当服务器无法通过另一种方式来确定语言时使用的提示,例如由明确的用户决定控制的特定URL。
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");