Search code examples
c#asp.net-coredependency-injectionmicroservicesasp.net-core-webapi

Get client's IP address in ASP.NET Core 2.2


I have created an micro services application in asp.net core 2.2. I want to fetch out the IP address of the user from where he is using it.

The below snippet provides the ip address of the hosted server.

var remoteIpAddress = request.HttpContext.Connection.RemoteIpAddress;

I want to get the ip address of the user who is using the APIs for audit log purpose.


Solution

  • Inject IHttpContextAccessor

    And put the below snippet

    var result = string.Empty;
    
     //first try to get IP address from the forwarded header
                    if (_httpContextAccessor.HttpContext.Request.Headers != null)
                    {
                        //the X-Forwarded-For (XFF) HTTP header field is a de facto standard for identifying the originating IP address of a client
                        //connecting to a web server through an HTTP proxy or load balancer
    
                        var forwardedHeader = _httpContextAccessor.HttpContext.Request.Headers["X-Forwarded-For"];
                        if (!StringValues.IsNullOrEmpty(forwardedHeader))
                            result = forwardedHeader.FirstOrDefault();
                    }
    
                    //if this header not exists try get connection remote IP address
                    if (string.IsNullOrEmpty(result) && _httpContextAccessor.HttpContext.Connection.RemoteIpAddress != null)
                        result = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
    

    I think it may work.