在ASP.NET中,使用負載均衡時,能夠經過ServerVariables獲取客戶端的IP地址。負載均衡
var ip = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
但在ASP.NET Core中沒有ServerVariables的對應實現,須要換一種方式,能夠在HttpContext.Request.Headers中獲取,須要注意的是key與ServerVariables方式不同,ServerVariables中是"HTTP_X_FORWARDED_FOR",HttpContext.Request.Headers中是"X-Forwarded-For",示例代碼以下:this
var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
完整的擴展方法實現以下:spa
public static class HttpContextExtension { public static string GetUserIp(this HttpContext context) { var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault(); if (string.IsNullOrEmpty(ip)) { ip = context.Connection.RemoteIpAddress.ToString(); } return ip; } }