How to Get Client IP Address in ASP.NET Core 2.0 Razor Pages

In this short post, find the code to get client IP address in ASP.NET Core 2.0 Razor pages. You need to inject IHttpContextAccessor in razor page using @inject. You can inject a service into a view using the @inject directive. You can think of @inject as adding a property to your view, and populating the property using DI.

@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor

Once injected, then you can use it in following way to get the IP address.

Client IP Address : @HttpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString()

Use the same service in the following way in code behind file.

private IHttpContextAccessor _accessor;

public DemoModel(IHttpContextAccessor httpContextAccessor)
{
    _accessor = httpContextAccessor;
}
public void OnGet()
{
    ClientIPAddress = "_accessor.HttpContext.Connection.RemoteIpAddress.ToString();
}

When you run the application in the local, the code will return the result “::1” but it will work once you deploy your application.

Simply and easy. Thank you for reading. Keep visiting this blog and share this in your network. Please put your thoughts and feedback in the comments section.

2 thoughts on “How to Get Client IP Address in ASP.NET Core 2.0 Razor Pages

Leave a Reply

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

11 + 2 =