using System; using System.Collections.Generic; using System.Text; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; namespace TEAMModelOS.SDK.Extension { public static class HttpContextExtensions { /// /// 取得驗證金鑰,Authorization /// public static string GetToken(this HttpContext httpContext) { return httpContext.Request.Headers["Authorization"].ToString(); } /// /// 取得JWT驗證金鑰,Authorization Bearer /// /// /// public static string GetJwtToken(this HttpContext httpContext) { var token = string.Empty; string authorization = httpContext.Request.Headers["Authorization"].ToString(); if (!string.IsNullOrWhiteSpace(authorization) && authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) { token = authorization.Substring("Bearer ".Length).Trim(); } return token; } /// /// 取得遠端呼叫的IP /// public static string GetRemoteIP(this HttpContext httpContext) { return httpContext?.Connection?.RemoteIpAddress?.ToString(); } /// /// 取得X-Auth-Key值 /// /// Key Name /// public static string GetXAuth(this HttpContext httpContext, string key = null) { try { if (httpContext.Request.Headers.TryGetValue($"X-Auth-{key}", out StringValues value)) return value.ToString(); else return null; } catch { return null; } } /// /// 取得User-Agent值 /// public static string GetUserAgent(this HttpContext httpContext) { try { return httpContext.Request.Headers["User-Agent"].ToString(); } catch { return null; } } /// /// 取得Scheme值 /// public static string GetScheme(this HttpContext httpContext) { return httpContext?.Request?.Scheme; } /// /// 取得HostName值 /// public static string GetHostName(this HttpContext httpContext) { return httpContext?.Request?.Host.ToString(); } } }