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?
Asked
Active
Viewed 291 times
-2

Ivan
- 7,448
- 14
- 69
- 134
-
See this : http://bekenty.com/how-to-get-client-ip-address-in-asp-net-core/ – Nan Yu Feb 11 '20 at 04:43
-
Please read [ask]. – CodeCaster Feb 11 '20 at 06:11
-
Does this answer your question? [How do I get client IP address in ASP.NET CORE?](https://stackoverflow.com/questions/28664686/how-do-i-get-client-ip-address-in-asp-net-core) – CodeCaster Feb 11 '20 at 06:13
1 Answers
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