c# 中的服务器变量中缺少 HTTP_X_FORWARDED_FOR
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17521277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTTP_X_FORWARDED_FOR missing from servervariables in c#
提问by thomvlau
I would like to get the ClientIPaddress but when I call to Request.ServerVariables["HTTP_X_FORWARDED_FOR"]I always get NULL.
我想获得 ClientIPaddress,但是当我打电话给Request.ServerVariables["HTTP_X_FORWARDED_FOR"]我时,我总是得到NULL.
After checking the list of the ServervariablesI noticed that HTTP_X_FORWARDED_FORis not in the list of options.
检查列表后,Servervariables我注意到HTTP_X_FORWARDED_FOR不在选项列表中。
Anyone knows how this is possible and how to solve? Or is it normal that this option is not in the list and I'm missing something.
任何人都知道这是怎么可能的以及如何解决?或者这个选项不在列表中并且我遗漏了一些东西是否正常。
Thanks in advance
提前致谢
回答by dwtm.ts
Request.ServerVariables["HTTP_X_FORWARDED_FOR"]will only have a value, if the request was forwarded by a proxy. Usually you will get the client IP by using Request.ServerVariables["REMOTE_ADDR"].
Request.ServerVariables["HTTP_X_FORWARDED_FOR"]如果请求是由代理转发的,则只有一个值。通常你会通过使用Request.ServerVariables["REMOTE_ADDR"].
回答by George Kosmidis
Please try this:
请试试这个:
public static string GetUserIP() {
var ip = ( HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null
&& HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != "" )
? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
: HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (ip.Contains( "," ))
ip = ip.Split( ',' ).First();
return ip.Trim();
}
Found here:
http://mycodepad.wordpress.com/2013/04/26/c-getting-a-user-ip-behind-a-proxy-http_x_forwarded_for/
在这里找到:http:
//mycodepad.wordpress.com/2013/04/26/c-getting-a-user-ip-behind-a-proxy-http_x_forwarded_for/
回答by Bahman Hero
public string GetIPAddress()
{
System.Web.HttpContext context = System.Web.HttpContext.Current;
string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ipAddress))
{
string[] addresses = ipAddress.Split(',');
if (addresses.Length != 0)
{
return addresses[0];
}
}
return context.Request.ServerVariables["REMOTE_ADDR"];
}
This method maybe useful for you.
这个方法可能对你有用。
回答by Hamid Talebi
If you run it on local machine , it's normal to don't see any thing, otherwise you run it in on a real external host.
如果你在本地机器上运行它,看不到任何东西是正常的,否则你在一个真正的外部主机上运行它。

