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.


About the author

DEJAN STOJANOVIC

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

JavaScript

read more

SQL/T-SQL

read more

Umbraco CMS

read more

PowerShell

read more

Comments for this article