C# X-Forwarded-For:如何获得客户';ASP.NETMVC中的IP地址?
我对asp.net mvc堆栈完全陌生,我想知道Request.Header对象发生了什么 基本上,我想做的是拉出设备(PC)IP地址,但无法检索到所需的输出。我还尝试了Request.ServerVariables对象,但结果始终保持为空 我正在使用asp.NETMVC。此功能是否需要更改:C# X-Forwarded-For:如何获得客户';ASP.NETMVC中的IP地址?,c#,asp.net,asp.net-mvc,C#,Asp.net,Asp.net Mvc,我对asp.net mvc堆栈完全陌生,我想知道Request.Header对象发生了什么 基本上,我想做的是拉出设备(PC)IP地址,但无法检索到所需的输出。我还尝试了Request.ServerVariables对象,但结果始终保持为空 我正在使用asp.NETMVC。此功能是否需要更改: public static string GetIP() { string functionReturnValue = null; //Gets IP of act
public static string GetIP()
{
string functionReturnValue = null;
//Gets IP of actual device versus the proxy (WAP Gateway)
functionReturnValue = HttpContext.Current.Request.Headers["X-FORWARDED-FOR"]; //functionReturnValue = null
if (string.IsNullOrEmpty(functionReturnValue))
{
functionReturnValue = HttpContext.Current.Request.Headers["X-Forwarded-For"];//functionReturnValue = null
if (string.IsNullOrEmpty(functionReturnValue))
{
//If not using a proxy then get the device IP
// GetIP = Context.Request.ServerVariables("REMOTE_ADDR")
if (string.IsNullOrEmpty(functionReturnValue))
{
//If not using a proxy then get the device IP
functionReturnValue = HttpContext.Current.Request.Headers["X-CLIENT-IP"];//functionReturnValue = null
if (string.IsNullOrEmpty(functionReturnValue))
{
//If not using a proxy then get the device IP
functionReturnValue = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];//functionReturnValue = "::1"
}
}
}
}
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("(\\d{1,3}\\.){3}\\d{0,3}");
if (functionReturnValue != null)
{
if (regex.IsMatch(functionReturnValue))
{
functionReturnValue = regex.Match(functionReturnValue).Value.ToString();
}
else
{
functionReturnValue = "";
}
regex = null;
}
if (functionReturnValue == null)
{
return "";
}
else
{
return functionReturnValue;
}
}
在X-Forwarded-For中,您将获得客户端
ip
,proxy1
和proxy2
。通过获取第一项,您将获得客户端/用户ip
HttpContext.Current.Request.Headers["X-Forwarded-For"].Split(new char[] { ',' }).FirstOrDefault()
希望有帮助 在X-Forwarded-For中,您将获得客户端
ip
,proxy1
&proxy2
。通过获取第一项,您将获得客户端/用户ip
HttpContext.Current.Request.Headers["X-Forwarded-For"].Split(new char[] { ',' }).FirstOrDefault()
希望有帮助 你的问题和这篇文章很相似。你的问题和这篇文章很相似。