如何在 .net 标准中获取客户端的 ip 地址?

How to get the client's ip address in .net standard?

我需要在 .net 标准 2.1 class 库应用程序中获取客户端的 IP 地址。

我正在使用下面的代码,它在 .net 框架中按预期工作,但在 .net 标准中出现编译错误。

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

您正在使用 .NET Standard,它不包含诸如(HttpRequest 及其扩展方法)之类的依赖项,因此您需要安装链接到 HttpRequest 的 Nuget 包或转换您的 .NET 标准项目到 .NET WebApp。前一个包含持有 HttpRequest 的包。

参考:

我用过这个并且对我有用:

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

    }