using Microsoft.AspNetCore.Http; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace Hncore.Infrastructure.Core.Web { public static class HttpContextExtension { public static string GetUserIp(this HttpContext context) { var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault(); if (string.IsNullOrEmpty(ip)) { ip = context.Connection.RemoteIpAddress.ToString(); } return ip; } public static string GetAbsoluteUri(this HttpRequest request) { return new StringBuilder() .Append(request.Scheme) .Append("://") .Append(request.Host) .Append(request.PathBase) .Append(request.Path) .Append(request.QueryString) .ToString(); } public static async Task ReadBodyAsStringAsync(this HttpRequest request) { request.EnableBuffering(); var requestReader = new StreamReader(request.Body); var requestBody = await requestReader.ReadToEndAsync(); request.Body.Position = 0; return requestBody; } } public static class IsLocalExtension { private const string NullIpAddress = "::1"; public static bool IsLocal(this HttpRequest req) { var connection = req.HttpContext.Connection; if (connection.RemoteIpAddress.IsSet()) { return connection.LocalIpAddress.IsSet() ? connection.RemoteIpAddress.Equals(connection.LocalIpAddress) : IPAddress.IsLoopback(connection.RemoteIpAddress); } return true; } private static bool IsSet(this IPAddress address) { return address != null && address.ToString() != NullIpAddress; } } }