.NET Core经Cloudflare代理后获取用户真实IPv4地址的方法
Hey there! I’ve dealt with this exact scenario working with Cloudflare and ASP.NET before—let me walk you through how to fix it.
When Cloudflare acts as your reverse proxy, the RemoteIpAddress your server sees will always be a Cloudflare node IP, since the request routes through Cloudflare first. But don’t worry—Cloudflare passes the user’s real IP along in dedicated request headers, which we can leverage.
1. Use Cloudflare’s dedicated request header first
Cloudflare adds a CF-Connecting-IP header to every forwarded request. This is the most reliable source for the real user IP, because it’s a Cloudflare-specific header that can’t be tampered with by end users (unlike the more generic X-Forwarded-For).
2. Implement the IP retrieval logic in ASP.NET
Modify your code to check for this header first, then fall back to other options if needed. Here’s a robust example:
public string GetRealUserIp(HttpContext context) { // Priority 1: Grab Cloudflare's official real IP header var cfRealIp = context.Request.Headers["CF-Connecting-IP"].FirstOrDefault(); if (!string.IsNullOrEmpty(cfRealIp) && IPAddress.TryParse(cfRealIp, out var cfIp) && cfIp.AddressFamily == AddressFamily.InterNetwork) { return cfIp.MapToIPv4().ToString(); } // Priority 2: Fallback to X-Forwarded-For (handle potential multiple IPs) var xForwardedFor = context.Request.Headers["X-Forwarded-For"].FirstOrDefault(); if (!string.IsNullOrEmpty(xForwardedFor)) { // X-Forwarded-For format is usually "RealIP, ProxyIP1, ProxyIP2..." var firstIp = xForwardedFor.Split(',').First().Trim(); if (IPAddress.TryParse(firstIp, out var xIp) && xIp.AddressFamily == AddressFamily.InterNetwork) { return xIp.MapToIPv4().ToString(); } } // Last resort: Use the direct connection IP (Cloudflare's node) return context.Connection.RemoteIpAddress?.MapToIPv4().ToString() ?? "Unknown"; }
3. Lock down security to prevent IP spoofing
To make sure malicious users can’t fake the CF-Connecting-IP or X-Forwarded-For headers:
- Restrict server access to Cloudflare IPs only: Configure your firewall (Nginx, IIS, or cloud provider security groups) to allow traffic only from Cloudflare’s published IP ranges.
- Validate the source IP in code: Add a check to confirm the incoming
RemoteIpAddressbelongs to Cloudflare’s IP list before trusting the header values.
This way you’ll reliably get the real user IP while keeping your app secure.
内容的提问来源于stack exchange,提问作者fatnjazzy

