简体   繁体   中英

Detecting user IP address connecting behind cloudflare

I have a piece of code like following:

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

This is supposed to help me to figure out real IP address of the user connecting to my website through cloudflare...

The problem is that I don't know how do I call now this extension method through my controller:

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

Can someone help me out ?

The Request object is present in the action scope

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

don't forget to import your extension method with

using RequestExtensionsNamespance

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM