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.
This was very helpful! Although I have a basic project I’m using this in and got an error, and IHttpContextAccessor is no longer included by default per https://github.com/aspnet/Hosting/issues/793. I just had to add `services.AddSingleton();` into my Startup.cs and this is now working perfectly.
Thank you for this. Was working on this for hours and could not figure out why it wasnt working. Turns out it was. I just wasnt aware it would be …1 in the dev environment. This was the piece I was missing