From 010213d4a2ba3278a861f133f156fbcd3a4adf4f Mon Sep 17 00:00:00 2001 From: Young Date: Mon, 30 Sep 2024 23:26:22 +0800 Subject: [PATCH] added http context extension --- .../Utils/HttpContextExtension.cs | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/Infrastructure/Utils/HttpContextExtension.cs diff --git a/src/Infrastructure/Utils/HttpContextExtension.cs b/src/Infrastructure/Utils/HttpContextExtension.cs new file mode 100644 index 0000000..4d7ec90 --- /dev/null +++ b/src/Infrastructure/Utils/HttpContextExtension.cs @@ -0,0 +1,39 @@ +using Microsoft.AspNetCore.Http; + +namespace Infrastructure.Utils; + +public static class HttpContextExtension +{ + public static string? GetRequestIp(this HttpContext context) + { + var ip = context.GetRequestHeaderValue("X-Forwarded-For"); + if (!string.IsNullOrEmpty(ip) || context.Connection.RemoteIpAddress == null) + { + return ip; + } + + ip = context.Connection.RemoteIpAddress.MapToIPv4().ToString(); + if (string.IsNullOrEmpty(ip)) + { + ip = context.GetRequestHeaderValue("REMOTE_ADDR"); + } + + return ip; + } + + public static T? GetRequestHeaderValue(this HttpContext context, string headerName) + { + if (!context.Request.Headers.TryGetValue(headerName, out var value)) + { + return default; + } + + var valueStr = value.ToString(); + if (!string.IsNullOrEmpty(valueStr) || !string.IsNullOrWhiteSpace(valueStr)) + { + return (T)Convert.ChangeType(valueStr, typeof(T)); + } + + return default; + } +} \ No newline at end of file