Small ASP.NET Core helpers for local-request checks, Basic authentication challenges, and proxy-aware client IP lookup.
dotnet add package Soenneker.Extensions.HttpContextusing Soenneker.Extensions.HttpContext;
if (httpContext.IsLocalRequest())
{
// Apply behavior intended only for requests from this host.
}IsLocalRequest() returns true when the remote address is loopback, matches the local connection address, or both addresses are absent. It returns false when only the remote address is absent. It examines the connection addresses after any middleware that may have rewritten them.
httpContext.SetUnauthorized();
return;SetUnauthorized() sets status code 401 and adds WWW-Authenticate: Basic unless a challenge header already exists. It does not write a response body or end request processing, so return from the endpoint or middleware after calling it.
string? clientIp = httpContext.GetRequestIp();The lookup order is:
- A valid IP address in
CF-Connecting-IP. - The first address in
X-Forwarded-For, when it is a valid IP address. HttpContext.Connection.RemoteIpAddress.
Forwarding headers are supplied by the caller and can be spoofed unless your edge proxy removes incoming copies and writes trusted values. Only use the returned forwarded address for authorization, rate limiting, or auditing when that trust boundary is enforced. In standard ASP.NET Core deployments, prefer configuring Forwarded Headers Middleware and then reading RemoteIpAddress directly when possible.
Malformed or blank forwarding values are ignored. If no usable address is available, GetRequestIp() returns null.
