| 1 | namespace Microsoft.AspNetCore.Http; |
| 2 | |
| 3 | public static class HttpContextExtensions |
| 4 | { |
| 5 | public static string ResolveClientIpAddress(this HttpContext httpContext) |
| 6 | { |
| 7 | if (httpContext.Request.Headers.TryGetValue("Cf-Connecting-Ip", out var cfIp) && !string.IsNullOrEmpty(cfIp)) |
| 8 | return cfIp.ToString(); |
| 9 | |
| 10 | if (httpContext.Request.Headers.TryGetValue("X-Real-Ip", out var ip) && !string.IsNullOrEmpty(ip)) |
| 11 | return ip.ToString(); |
| 12 | |
| 13 | if (httpContext.Request.Headers.TryGetValue("X-Forwarded-For", out var forwardedIp) && !string.IsNullOrEmpty(forwardedIp)) |
| 14 | return forwardedIp.ToString(); |
| 15 | |
| 16 | var cfViewerAddress = httpContext.Request.Headers["CloudFront-Viewer-Address"]; |
| 17 | if (cfViewerAddress.Count > 0) |
| 18 | { |
| 19 | var parts = (cfViewerAddress[0] ?? string.Empty).Split(":"); |
| 20 | if (parts.Length == 1) |
| 21 | return parts[0]; |
| 22 | |
| 23 | if (parts.Length >= 1) |
| 24 | return string.Join(":", parts[0..^1]); |
| 25 | } |
| 26 | |
| 27 | return httpContext.Connection.RemoteIpAddress?.ToString() ?? ""; |
| 28 | } |
| 29 | |
| 30 | public static async Task EnsureSuccessWithLog(this HttpResponseMessage response, ILogger logger) |
| 31 | { |
| 32 | if (!response.IsSuccessStatusCode) |
| 33 | { |
| 34 | var responseBody = await response.Content.ReadAsStringAsync(); |
| 35 | logger.LogError("Request failed with {StatusCode} with body {ResponseBody}", response.StatusCode, responseBody); |
| 36 | response.EnsureSuccessStatusCode(); |
| 37 | } |
| 38 | } |
| 39 | } |
nothing calls this directly
no outgoing calls
no test coverage detected