本篇記錄如何使用asp.net core獲取真實的IP地址。
實際在使用的過程中,如果需要獲取客戶端地址,
是沒有辦法直接通過傳統ASP.Net使用Request.xxx的方式獲取的。
那么就需要進行如下操作:
1、新增一個依賴注入
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
2、控制器
private readonly IHttpContextAccessor _httpContextAccessor; public TestController( IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor;
}
3、使用
string ipaddress = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
通過上面的方法可以正常獲取到IP地址。
但是如果有使用Nginx做反向代理的話,使用上面的方式獲取到的IP會是127.0.0.1,無法獲取到真實的IP地址,
所以如果使用Nginx做反向代理,則應該使用下面的方式:
if (Request.Headers.ContainsKey("X-Real-IP")) { sb.AppendLine($"X-Real-IP:{Request.Headers["X-Real-IP"].ToString()}"); } if (Request.Headers.ContainsKey("X-Forwarded-For")) { sb.AppendLine($"X-Forwarded-For:{Request.Headers["X-Forwarded-For"].ToString()}"); }
因為實際使用,我們是無法通過RemoteIpAddress直接獲取到真實的客戶端地址的。
如果一定要使用,那么可以通過添加中間件的方式
public class RealIpMiddleware { private readonly RequestDelegate _next; public RealIpMiddleware(RequestDelegate next) { _next = next; } public Task Invoke(HttpContext context) { var headers = context.Request.Headers; if (headers.ContainsKey("X-Forwarded-For")) { context.Connection.RemoteIpAddress=IPAddress.Parse(headers["X-Forwarded-For"].ToString().Split(',', StringSplitOptions.RemoveEmptyEntries)[0]); } return _next(context); } }
在Startup中的Configura添加下面一句
app.UseMiddleware<RealIpMiddleware>();
這樣既可正常使用RemoteIpAddress獲取Nginx反向代理后的IP地址了。
Over!