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.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

    public class IPAddressController : ControllerBase
        private readonly IHttpContextAccessor httpContextAccessor;
        public IPAddressController(IHttpContextAccessor httpContextAccessor)
            this.httpContextAccessor = httpContextAccessor;

        public IActionResult Get()
            return Content(this.httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());


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.

About the author


Dejan is a passionate Software Architect/Developer. He is highly experienced in .NET programming platform including ASP.NET MVC and WebApi. He likes working on new technologies and exciting challenging projects

CONNECT WITH DEJAN  Loginlinkedin Logintwitter Logingoogleplus Logingoogleplus


read more


read more

Umbraco CMS

read more


read more

Comments for this article