WebAPI请求获取请求中的真实地址

发布时间 2023-07-20 08:56:52作者: 晚霞起风了

public static string WebAPIGetRealIP(this HttpRequest req)
{
string ipAddress = req.Headers["x-forwarded-for"].ToString()?.Trim();
if (!string.IsNullOrEmpty(ipAddress) && ipAddress.IndexOf(",") != -1)
{
ipAddress = ipAddress.Split(",")[0];
}
if (string.IsNullOrEmpty(ipAddress) || string.IsNullOrWhiteSpace(ipAddress))
{
ipAddress = req.Headers["Proxy-Client-IP"];
}
if (string.IsNullOrEmpty(ipAddress) || string.IsNullOrWhiteSpace(ipAddress))
{
ipAddress = req.Headers["WL-Proxy-Client-IP"];
}
if (string.IsNullOrEmpty(ipAddress) || string.IsNullOrWhiteSpace(ipAddress))
{
ipAddress = req.Headers["HTTP_CLIENT_IP"];
}
if (string.IsNullOrEmpty(ipAddress) || string.IsNullOrWhiteSpace(ipAddress))
{
ipAddress = req.Headers["HTTP_X_FORWARDED_FOR"];
}
if (string.IsNullOrEmpty(ipAddress) || string.IsNullOrWhiteSpace(ipAddress))
{
ipAddress = req.Headers["X-Real-IP"];
}
if (string.IsNullOrEmpty(ipAddress) || string.IsNullOrWhiteSpace(ipAddress))
{
ipAddress = req.HttpContext.Connection.RemoteIpAddress?.MapToIPv4().ToString();
}
if (ipAddress == "::1")
{
ipAddress = "127.0.0.1";
}
if (string.Equals(ipAddress, "127.0.0.1") && req.Headers.ContainsKey("X-Forwarded-For"))
{
ipAddress = req.Headers["X-Forwarded-For"].ToString();
if (ipAddress.IndexOf(",") != -1)
{
ipAddress = ipAddress.Split(",")[0];
}
}
if (string.IsNullOrEmpty(ipAddress) || string.IsNullOrWhiteSpace(ipAddress))
{
return string.Empty;
}
return ipAddress;
}