0

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?

Jinxing Li
  • 1
  • 1
  • 6
  • Have you checked whether it is Request that is null or ServerVariables? – Kzryzstof Apr 25 '18 at 10:37
  • What line threw the exception ? – Rainbow Apr 25 '18 at 10:39
  • how to check? as this method is in tool class, Do I need initialize Request and how? I am fresh on C#. – Jinxing Li Apr 25 '18 at 10:40
  • @ZohirSalakCeNa this line: _stringIpAddress = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; – Jinxing Li Apr 25 '18 at 10:41
  • I found this - https://stackoverflow.com/questions/17521277/http-x-forwarded-for-missing-from-servervariables-in-c-sharp?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Rainbow Apr 25 '18 at 10:57
  • @ZohirSalakCeNa, tried 'HTTP_CONNECTION', but same error show up. So, it means no Request caught? – Jinxing Li Apr 25 '18 at 10:59
  • Hum...Interesting, When do you call your function ? – Rainbow Apr 25 '18 at 11:02
  • Try this `var current = System.Web.HttpContext.Current; var request = current.Request; var ServerVariables = request.ServerVariables["HTTP_X_FORWARDED_FOR"]; _stringIpAddress = ServerVariables;` add breakpoint and the beginning and see which one of them throws the exception. – Rainbow Apr 25 '18 at 11:27

0 Answers0