How to get client IP Address in ASP.NET Core 2
Fetching client IP address in ASP.NET Core
As ASP.NET was evolving, there were different ways accessing client IP address from the request. The way to do it WebForms and MVC Web application is simply accessing request of the current HTTP context
var ip = HttpContext.Current.Request.UserHostAddress;
Or just simply referencing to the current Request directly
var ip = Request.UserHostAddress;
However this will not work in ASP.NET Core 2.0 and onwards. You have to inject HttpContextAccessor instance from the Startup.cs class in ConfigureServices method
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); }
Now we need to have it in our controller constructor and assign in to a controller level declared variable. This way it is accessible from all Actions in a controller
[Route("api/[controller]")] [ApiController] public class IPAddressController : ControllerBase { private readonly IHttpContextAccessor httpContextAccessor; public IPAddressController(IHttpContextAccessor httpContextAccessor) { this.httpContextAccessor = httpContextAccessor; } [HttpGet] public IActionResult Get() { return Content(this.httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString()); } }
Disclaimer
Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.
Comments for this article