2

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

Andrew Simpson
  • 6,883
  • 11
  • 79
  • 179

1 Answers1

2

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.

Bruno Farias
  • 785
  • 8
  • 22
  • Thanks. I just found that info just before I posted. I will have to try this tomorrow. If it works I will accept ur answer. Thanks again – Andrew Simpson Jun 27 '20 at 20:51
  • 1
    Thanks. there was actually flawed logic in my code. I was tired yesterday :(. But this answer is succinct and may help others. thanks for your time – Andrew Simpson Jun 28 '20 at 04:40