0

How to get in ASP.NET Core 3.0 API the client API

On the start up class I have added this line:

services.AddControllersWithViews();
services.AddSingleton <IActionContextAccessor,ActionContextAccessor>();

IndexController.cs

    private readonly IActionContextAccessor _accessor;
    public IndexController(IActionContextAccessor accessor) 
    {
            _accessor = accessor;
    }


    [HttpGet()]
    [Route("[action]")]
    public string GetIPAddress(string id)
    {
        //var ip = HttpContext.Connection.RemoteIpAddress.ToString();
        var ip = _accessor.ActionContext.HttpContext.Connection.RemoteIpAddress.ToString();
        return ip;

    }

After trying many methods, we can't get the IP address of the client. The result is:
::1

A_kat
  • 1,459
  • 10
  • 17
yingshao
  • 41
  • 2
  • Possible duplicate of https://stackoverflow.com/questions/28664686/how-do-i-get-client-ip-address-in-asp-net-core . See the accepted answers comments – A_kat Feb 19 '20 at 10:22

1 Answers1

1

If you're developing locally with localhost, this is normal and you should be able to get the IP address you're looking for when you publish to production (it's probably worth testing at staging first).

If you're wondering why, it's to do with the loopback address, take a look here for more information.

Shoejep
  • 4,414
  • 4
  • 22
  • 26