How to Get client ip address in .net core 2.x

March 16, 2019 0 comments
To get client IP address in Asp.net core 2.x, you have to inject HttpContextAccessor 

Declare private variable in class


   private IHttpContextAccessor _accessor;


Initialize above private variable in default constructor and retrieve IP address as showed in following code


public class HomeController : Controller
    {
        private readonly IUserRepository userRepository;
        private IHttpContextAccessor _accessor;

        public HomeController(IUserRepository userRepository,
        IHttpContextAccessor accessor)
        {
            this.userRepository = userRepository;
            this._accessor = accessor;
        }
        public IActionResult Index()
        {
   ViewBag.IpAddress = 
_accessor.HttpContext.Connection.RemoteIpAddress.ToString();
   return View();
        }
    }



Make sure you initialize IHTTPContextAccessor in startup.cs


services.TryAddSingleton<ihttpcontextaccessor httpcontextaccessor="">();
</ihttpcontextaccessor>


If you don't register IHTTPContextAccessor .net core will give you following error

 InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' while attempting to activate

.net core get host ip address

Get Client ip address in .net core 2.0

Share Share Tweet Share

0 thoughts on "How to Get client ip address in .net core 2.x"

LEAVE A REPLY