Are que getting null or empty with some Request.ServerVariables
When you convert your ASP application to run on Windows Azure it is a good
to put attention to the methods that are used to get the user IP Address.
Normally the recommendation will be to use Request.UserHostAddress however
our friend Alex has found that this property can return null or empty.
After some research Alex found that there are several scenarios under which
you must check both the REMOTE_ADDR and the HTTP_X_FORWARD_FOR server variables:
More info:
http://forums.asp.net/t/1138908.aspx and
http://meatballwiki.org/wiki/AnonymousProxy
A possible code snipped that can provide a value for the client address can be:
public static string ReturnIP()
{
var request = System.Web.HttpContext.Current.Request;
var ServerVariables_HTTP_X_FORWARDED_FOR = (String)request.ServerVariables["HTTP_X_FORWARDED_FOR"];
var ServerVariables_REMOTE_ADDR = (String)request.ServerVariables["REMOTE_ADDR"];
string ip = "127.0.0.1";
if (!string.IsNullOrEmpty(ServerVariables_HTTP_X_FORWARDED_FOR) &&
!ServerVariables_HTTP_X_FORWARDED_FOR.ToLower().Contains("unknown"))
{
ServerVariables_HTTP_X_FORWARDED_FOR = ServerVariables_HTTP_X_FORWARDED_FOR.Trim();
string[] ipRange = ServerVariables_HTTP_X_FORWARDED_FOR.Split(',');
ip = ipRange[0];
}
else if (!string.IsNullOrEmpty(ServerVariables_REMOTE_ADDR))
{
ServerVariables_REMOTE_ADDR = ServerVariables_REMOTE_ADDR.Trim();
ip = ServerVariables_REMOTE_ADDR;
}
return ip;
}
In the previous code the HTTP_X_FORWARDED_FOR value is examined first and if it is not null or unknown then ip address of the client
is gotten from there.