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?)

0

2 Answers 2

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 "";
        }

    }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I am able to build the solution successfully, I will check whether is it giving the expected result and let you know
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

1 Comment

I have already added Microsoft.AspNetCore.Http.Abstractions and Microsoft.AspNet.Mvc` packages, please let me know if I need to add others

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.