I want to get the client IP address in tool class, but I got an error when calling Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
. The error message is:
Object reference not set to an instance of an object
Here is the code :
public static string GetIpAddress()
{
string _stringIpAddress = string.Empty;
try
{
_stringIpAddress = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (_stringIpAddress == null)
{
_stringIpAddress = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
}
catch (Exception ex)
{
Logging.LogError(string.Concat("GetIpAddress()", ex.Message));
}
return _stringIpAddress;
}
How can I fix it?