直接用 扩展

    public static string GetRemoteIPAddress(this HttpContext context, bool allowForwarded = true)
    {
        if (allowForwarded)
        {
            string? header = context.Request.Headers["CF-Connecting-IP"].FirstOrDefault() ?? context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (!string.IsNullOrEmpty(header) && IPAddress.TryParse(header, out var ip))
            {
                return ip.ToString();
            }
        }
        var _ip = context.Connection.RemoteIpAddress;

        string res = "";
        if (_ip != null)
        {
            if (_ip.IsIPv4MappedToIPv6)
                res = _ip.MapToIPv4().ToString();
            else
                res = _ip.ToString();
        }
        return res;
    }

使用:

string ip = HttpContext.GetRemoteIPAddress();

标签: none

添加新评论