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) Razor Pages.
Note: For beginners in ASP.Net Core (.Net Core 7) Razor Pages, please refer my article ASP.Net Core 7 Razor Pages: Hello World Tutorial with Sample Program example.
 
 

Razor PageModel (Code-Behind)

The IHttpContextAccessor is injected in the constructor of the IndexModel and assigned to the private property Accessor.
The PageModel consists of following Handler method.

Handler method for handling GET operation

Inside the Handler method, the IPAddress is fetched using the RemoteIpAddress property of the IHttpContextAccessor property and set into ViewData 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.
 
public class IndexModel : PageModel
{
    private IHttpContextAccessor Accessor { get; set; }
 
    public IndexModel(IHttpContextAccessor _accessor)
    {
        this.Accessor = _accessor;
    }
 
    public void OnGet()
    {
        ViewData["IPAddress"] = this.Accessor.HttpContext.Connection.RemoteIpAddress?.ToString();
    }
}
 
 

Razor Page (HTML)

HTML Markup

Inside the Razor Page, the IP Address is displayed using ViewData object.
@page
@model IPAddress_Core_Razor.Pages.IndexModel
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <h1>Your IP Address: @ViewData["IPAddress"]</h1>
</body>
</html>
 
 

Screenshot

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

Demo

 
 

Downloads