asp.net mvc获取访问者IP根据IP获取城市地址跳转到相应的页面 求大神!

2024-12-12 20:33:29
推荐回答(1个)
回答1:

给你一个获取IP的代码,然后根据获取的地区名去数据库匹配对应的城市或二级域名即可。

#region 获取IP
///


/// 客户端ip(访问用户)
///

public static string GetUserIp
{
get
{
string realRemoteIP = "";
if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
realRemoteIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].Split(',')[0];
}
if (string.IsNullOrEmpty(realRemoteIP))
{
realRemoteIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
if (string.IsNullOrEmpty(realRemoteIP))
{
realRemoteIP = System.Web.HttpContext.Current.Request.UserHostAddress;
}
return realRemoteIP;
}
}