Search code examples
c#asp.net-corenginxclientip

Get clients wan ip adddress when api controller is called


I have a JavaScript ajax call to my web api controller. I need to get their wan ip address when they make that call.

I have seen many examples for MVC but I am using asp.net core and the methods there do not work. The value(s) are always null.

This is js:

 $.ajax({
    url: "/my server ip",
    type: "POST",
    contentType: "application/json; charset=utf-8",
    headers: { 'Content-Type': 'application/json' },
    success: function (data) { 
         $("#DeviceIp").html(data.ip + " " + data.wanIp);
            }
        });

my api:

    IActionContextAccessor accessor

    _accessor = accessor;


    [HttpPost]
    [Route("Account/GetDeviceIp")]
    public IpStats GetDeviceIp()
    {
        var WanIp = _accessor.ActionContext.HttpContext.Request.Headers.ToString();
    }

NB

I should have said that this:

_accessor.ActionContext.HttpContext.Connection.RemoteIpAddress.ToString()

gave me null. The other method was not null but no wanip address on that object...

ALSO

I am using nginx and not IIS


Solution

  • The below Action in a regular .NET Core 2.2 Web Api controller works for me:

    [HttpGet]
    public string Get()
    {
        return HttpContext.Connection.RemoteIpAddress.ToString();
    }
    

    However, you mentioned you are using nginx (I assume as reverse proxy) and that changes where to get the IP address information from. When we use a reverse proxy, the proxy needs to put the client's IP address in a HTTP header X-Forwarded-For, then your application should be able to see client's real ip address:

    // using Microsoft.AspNetCore.HttpOverrides;
    
    app.UseForwardedHeaders(new ForwardedHeadersOptions
    {
        ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
    });
    

    so make sure you setup the X-Forwarded-For header as described in Host .NET Core in Linux with nginx (section Configure nginx), this tutorial covers all the basic setup you need.