ASP.Net Core 5-Getting the User's IP Address

For tallying the # of views on this website, we wanted to exclude our own hits while we developed. So, we needed to find the IP Address of the user. Real fast we found that the normal way of doing this under ASP.NET Core 5 would return the Apache Server local address (127.0.0.1). Searching the web, we were able to cobble some posts to find this solution.

-Raising Awesome ©2021

This is for a "webapp" (aka Razor Pages). It's the kind of app that you'd start with "dotnet new webapp" at the terminal.

Paste this at the top of your model file:

using System.Net;

Paste this before the final brace of your model file:


            public static class HttpContextExtensions
                {
                    public static IPAddress GetRemoteIPAddress(this HttpContext context, bool allowForwarded = true)
                    {
                        if (allowForwarded)
                        {
                            string header = (context.Request.Headers["CF-Connecting-IP"].FirstOrDefault() ?? context.Request.Headers["X-Forwarded-For"].FirstOrDefault());
                            if (IPAddress.TryParse(header, out IPAddress ip))
                            {
                                return ip;
                            }
                        }
                        return context.Connection.RemoteIpAddress;
                    }
                }
        


Last, in the routine where you want to discover it, put this:

string the_ip=HttpContext.GetRemoteIPAddress().ToString();