Getting the Client IP Address in ASP.NET Core

When I need to pick up the client IP Address in ASP.NET Core I always forget where to find the connection information.
It's also useful to remember that if requests are proxied we need to return the forwarded IP address, rather than the proxy's IP Address.
Good ready to use a small helper extension method for the HttpRequest class that makes this more easily accessible:
/// <summary>
/// Returns the client IP Address for a request.
///
/// Checks proxy forwarding first, then the actual ip
/// and returns null if not available.
/// </summary>
/// <param name="context">HttpRequest instance</param>
/// <returns>
/// IP Address or null if not available. Note local IP
/// tends to get returned as IPv6 `::1` value.
/// </returns>
public static string GetClientIpAddress(this HttpRequest request)
{
if (request == null) return null;
return request.Headers["X-Forwarded-For"].FirstOrDefault() ??
request.HttpContext?.Connection?.RemoteIpAddress?.ToString() ??
null;
}
You can also find this as part of the HttpRequestExtensions class in the Westwind.AspNetCore package here which provides a host of other small, but frequently used extensions.
Summary
Nothing new here, but given how often I fumble for this value, creating this wrapper and putting a reminder here for quick lookup seems worth the effort 😄
Resources
The Voices of Reason
# re: Getting the Client IP Address in ASP.NET Core
Thanks @Jon - Fixed. The Weblog site's gone through a major port and I'm still dealing with a few rough edges. Totally missed the bad Urls - was wondering why new posts weren't getting hit from the feed. This explains it 😄
# re: Getting the Client IP Address in ASP.NET Core
Hi Rick,
The links in your RSS feed are malformed:
https://weblog.west-wind.com/https://weblog.west-wind.com/posts/2026/May/13/Getting-the-Client-IP-Address-in-ASPNET-Core
Otherwise, love your content!