0

I need to get the client's IP address in .net standard 2.1 class library application.

I am using the code below, It works as expected in the .net framework, but its giving compilation error in .net standard.

private string IPAddress { get { return HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; } }

Error CS1061 'HttpRequest' does not contain a definition for 'ServerVariables' and no accessible extension method 'ServerVariables' accepting a first argument of type 'HttpRequest' could be found (are you missing a using directive or an assembly reference?)

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197

2 Answers2

1

I have used this and works for me:

    public static string GetLocalIpAddress()
    {
        try
        {
            using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
            {
                socket.Connect("8.8.8.8", 65530);
                var endPoint = socket.LocalEndPoint as IPEndPoint;
                Logger.LogMessage("Local Ip Address detected: " + endPoint.Address.ToString());
                return endPoint.Address.ToString();
            }
        }
        catch (Exception ex)
        {
            Logger.LogMessage(null, "Error obtaining local ip address:" + ex.Message);
            return "";
        }

    }
E.J. Brennan
  • 45,870
  • 7
  • 88
  • 116
  • Thank you, I am able to build the solution successfully, I will check whether is it giving the expected result and let you know – Vivek Nuna Jul 11 '20 at 12:48
0

You are using .NET Standard, which doesn't contain the dependencies such as (HttpRequest and its extensions methods), therefore you'd need to either install the Nuget packages linked to HttpRequest OR convert your .NET standard project to a .NET WebApp. The former one contains the packages holding your HttpRequest.

Reference: HttpContext in .net standard library

Bruno
  • 924
  • 9
  • 20
  • I have already added `Microsoft.AspNetCore.Http.Abstractions and `Microsoft.AspNet.Mvc` packages, please let me know if I need to add others – Vivek Nuna Jul 11 '20 at 12:41