c# - 检测在cloudflare后面连接的用户IP地址

标签 c# asp.net-mvc

我有一段代码如下:

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 地址...

问题是我不知道现在如何通过我的 Controller 调用这个扩展方法:

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

有人可以帮我吗?

最佳答案

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

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

不要忘记导入您的扩展方法

using RequestExtensionsNamespance

关于c# - 检测在cloudflare后面连接的用户IP地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51696143/

相关文章:

c# - Xamarin Android 上的振动

c# - ObservableCollection PropertyChanged 事件

javascript - 页面加载时无法调用 JavaScript 函数

c# - 网络 API 错误 : "No HTTP resource was found that matches the request URI"

c# - 从 MVC 放置/发布后如何获得 JSON 响应

c# - 识别twitter用户的经度和纬度

c# - Sitecore - 使用渲染引用动态渲染 View / Controller 渲染

asp.net-mvc - ASP.NET MVC Controller 中的构造函数依赖注入(inject)

asp.net-mvc - ASP.NET MVC 路由参数不适用于区域

asp.net - web.config 中与 targetFramework 相关的配置错误