In ASP. NET, when using load balancing, the IP address of the client can be obtained through ServerVariables.
var ip = Request. servervariables["http_x_forwarded_for"];
However, there is no corresponding implementation of ServerVariables in ASP. Can be obtained in the HttpContext.Request.Headers, it is important to note that the key is not the same as the ServerVariables way, ServerVariables is "http_x_forwarded_for", HttpContext.Request.Headers is "x-forwarded-for", the sample code is as follows:
var ip = context. request.headers["x-forwarded-for"]. FirstOrDefault ();
The complete extension method is implemented as follows:
Public Static classhttpcontextextension{ Public Static stringGetuserip ( ThisHttpContext context) { varIP = context. request.headers["x-forwarded-for"]. FirstOrDefault (); if(string. IsNullOrEmpty (IP)) {IP=context. Connection.RemoteIpAddress.ToString (); } returnIP; }}
How ASP. NET core obtains client IP address under load Balancing scenario