asp.net MVC 发布的放于服务器网站无法获取客户端IP

liusa1997 2019-04-03 06:31:32
当用户访问主页面会记录下用户的IP信息,但是我用了如下代码:(只能记录本机访问的IP,然而外网的无法记录)

/// <summary>
/// 获取web客户端ip
/// </summary>
/// <returns></returns>
public static string GetWebClientIp()
{

string userIP = "未获取用户IP";

try
{
if (System.Web.HttpContext.Current == null
|| System.Web.HttpContext.Current.Request == null
|| System.Web.HttpContext.Current.Request.ServerVariables == null)
{
return "";
}

string CustomerIP = "";

//CDN加速后取到的IP simone 090805
CustomerIP = System.Web.HttpContext.Current.Request.Headers["Cdn-Src-Ip"];
if (!string.IsNullOrEmpty(CustomerIP))
{
return CustomerIP;
}

CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

if (!String.IsNullOrEmpty(CustomerIP))
{
return CustomerIP;
}

if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
{
CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

if (CustomerIP == null)
{
CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
}
else
{
CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}

if (string.Compare(CustomerIP, "unknown", true) == 0 || String.IsNullOrEmpty(CustomerIP))
{
return System.Web.HttpContext.Current.Request.UserHostAddress;
}
return CustomerIP;
}
catch { }

return userIP;

}

由于服务器不好调试,所以不知道问题出在哪里,怎么解决这个问题?需要穿透吗?
...全文
51 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧