ASP.NET Core

How to get IP address in dotnet core

Follow the below steps for get IP address in dotnet core.

  1. Add Namespace in you controller
    using Microsoft.AspNetCore.Http;
  2. Create private variable for IHttpContextAccessor
     private IHttpContextAccessor _accessor;
  3. Add Dependency Injection in controller
     public TestController(IHttpContextAccessor accessor)
            {
                _accessor = accessor;
            }
  4. Change in your Startup.cs
    public void ConfigureServices(IServiceCollection services)
    {
        ...
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        ...
    }
  5. Get The IP Address
    _accessor.HttpContext.Connection.RemoteIpAddress.ToString()
    // if you user localhost then you will receive output ::1

     

Finally your controller should be look like below

 public class factorController : Controller
    {
        private IHttpContextAccessor _accessor;
        public factorController(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }
        [HttpGet]
        public IActionResult GetIPAddress()
        {
          return Content(_accessor.HttpContext.Connection.RemoteIpAddress.ToString());
        }
    }

 

 

Tags
Show More

Related Articles

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Close