In this article I will explain with an example, how to get Client IP Address of Visitor’s Machine in ASP.Net Core (.Net Core) MVC.
Note: For beginners in ASP.Net Core (.Net Core 7), please refer my article ASP.Net Core 7: Hello World Tutorial with Sample Program example.
 
 

Controller

The IHttpContextAccessor is injected in the constructor of the HomeController and assigned to the private property Accessor.
The Controller consists of following Action method.

Action method for handling GET operation

Inside the Action method, the IPAddress is fetched using the RemoteIpAddress property of the IHttpContextAccessor property and set into ViewBag object.
Note: While running this application on your machine locally i.e. in Visual Studio, the IP Address will show as 127.0.0.1 or ::1.
          This happens because in such case the Client and Server both are the same machine.
          Thus, no need to worry when you deploy it on a Server, you will see the results.
 
Finally, the View is returned.
public class HomeController : Controller
{
    private IHttpContextAccessor Accessor { get; set; }
 
    public HomeController(IHttpContextAccessor _accessor)
    {
        this.Accessor = _accessor;
    }
 
    public IActionResult Index()
    {
        ViewBag.IPAddress = this.Accessor.HttpContext.Connection.RemoteIpAddress?.ToString();
        return View();
    }
}
 
 

View

HTML Markup

Inside the View, the IP Address is displayed using ViewBag object.
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <h1>Your IP Address: @ViewBag.IPAddress</h1>
</body>
</html>
 
 

Screenshot

ASP.Net Core: How to get Client IP Address of Visitors Machine
 
 

Demo

 
 

Downloads