代码之家  ›  专栏  ›  技术社区  ›  User987

检测cloudflare背后连接的用户IP地址

  •  0
  • User987  · 技术社区  · 6 年前

    我有一段代码如下:

    public static class RequestExtensions
        {
            public static string GetIpAddress(this HttpRequestBase request)
            {
                if (request.Headers["CF-CONNECTING-IP"] != null)
                    return request.Headers["CF-CONNECTING-IP"];
    
                var ipAddress = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    
                if (!string.IsNullOrEmpty(ipAddress))
                {
                    var addresses = ipAddress.Split(',');
                    if (addresses.Length != 0)
                        return addresses[0];
                }
    
                return request.UserHostAddress;
            }
        }
    

    这应该可以帮助我找出通过cloudflare连接到我的网站的用户的真实IP地址。。。

    问题是,我现在不知道如何通过控制器调用此扩展方法:

    public actionresult Index()
    {
    // How do I now call the GetIpAddress extension method ??
    }
    

    有人能帮我吗?

    1 回复  |  直到 6 年前
        1
  •  3
  •   Bellash    6 年前

    请求对象存在于操作范围中

    public ActionResult Index()
     {
       // Here is how you now call the GetIpAddress extension method
       var ipString = this.Request.GetIpAddress();
    }
    

    别忘了用

    using RequestExtensionsNamespance