-2

I have a dotnet core ASP 3.1 MVC server app. I expose an HTTP GET through the controllers. Is there a way to get the IP address of the caller to the API?

Ivan
  • 7,448
  • 14
  • 69
  • 134

1 Answers1

0

you can use IHttpContextAccessor to get the IP. use this code in your controller:

[ApiController]
[Route("[controller]")]
public class YourController : ControllerBase
{

    private readonly IHttpContextAccessor accessor;

    public YourController (IHttpContextAccessor accessor)
    {
        this.accessor = accessor;
    }

    [HttpGet]
    public void Get()
    {
        var ip= accessor.HttpContext.Connection.RemoteIpAddress.ToString();
    }
}

and at the Startup.cs add this line of code to your ConfigureServices:

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    ...
}
Jafar ashrafi
  • 511
  • 6
  • 18
  • When hosting outside of IIS you may need to add Forwarded headers too https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-2.2 and `KnownProxies` may be necessary if more than 1 (reverse) proxy is used. Otherwise (if you cant use know networks) look into `ForwardLimit ` to control the forwarded for headers (which also includes remote IP in reverse proxy scenarios) – Tseng Feb 11 '20 at 07:09
  • To access HttpContext in Controller, injecting HttpContextAccessor is not required. ControllerBase already contains HttpContext. – Bob Ash Feb 11 '20 at 11:34
  • yes, of course there is httpcontext in controller base, But I suggest this if he wanted use in other class, he does it easily... @Bob – Jafar ashrafi Feb 11 '20 at 12:25