using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Alchemy.Core.Extensions { public static class HttpContextExtension { /// /// 获取请求的Referer /// /// /// public static string GetReferer(this HttpContext context) { return context.GetHeaderValue("Referer"); } /// /// 判断是否本地请求 /// /// /// public static bool IsLocalRequest(this HttpContext context) { return context.GetFromIp().Equals("127.0.0.1"); } /// /// 获取接口路由 /// /// /// public static string GetRoute(this HttpContext context) { return context.Request.Path; } /// /// 获取请求方法 /// /// /// public static string GetMethod(this HttpContext context) { return context.Request.Method; } /// /// 获取请求URL /// /// /// public static string GetRequestUrl(this HttpContext context) { return $"{context.Request.Scheme}://{context.Request?.Host}{context.Request?.Path}{context.Request?.QueryString}"; } /// /// 获取Authorization /// /// /// public static string GetAuthorization(this HttpContext context) { return context.GetHeaderValue("Authorization"); } /// /// 获取X-User-Token /// /// /// public static string GetXUserToken(this HttpContext context) { return context.GetHeaderValue("X-USER-TOKEN"); } /// /// 获取请求头的参数 /// /// /// /// public static string GetHeaderValue(this HttpContext context, string strKey) { if (context.Request.Headers.ContainsKey(strKey)) return context.Request.Headers[strKey].ToString(); else return string.Empty; } /// /// 获取UA /// /// /// public static string GetUserAgent(this HttpContext context) { return context.GetHeaderValue("User-Agent"); } /// /// 获取请求者IP /// /// /// public static string GetFromIp(this HttpContext context) { if (context.Connection.RemoteIpAddress.IsNull()) return string.Empty; else return context.Connection.RemoteIpAddress.ToString().Replace("::ffff:", ""); } /// /// 获取请求者端口 /// /// /// public static int GetFromPort(this HttpContext context) { return context.Connection.RemotePort; } /// /// 根据键获取请求的查询参数的值 /// /// /// /// public static string? GetQueryValue(this HttpContext context, string strKey) { return context.Request.Query[strKey]; } /// /// 获取请求的参数json,不分请求方式 /// /// /// public static async Task GetParamJson(this HttpContext context) { string strParamJson = string.Empty; string strMethod = context.GetMethod(); switch (strMethod) { case "GET": case "DELETE": strParamJson = context.GetQueryJson(); break; case "PUT": case "POST": strParamJson = await context.GetBodyJson(); break; } return strParamJson; } /// /// 获取请求的查询参数json /// /// /// public static string GetQueryJson(this HttpContext context) { JObject jo = new JObject(); foreach (string strKey in context.Request.Query.Keys) { jo.Add(strKey, context.Request.Query[strKey].ToString()); } return jo.ToJson(); } /// /// 获取请求的body参数json /// /// /// public static async Task GetBodyJson(this HttpContext context) { StreamReader stream = new StreamReader(context.Request.Body); string strRawJson = await stream.ReadToEndAsync(); return JsonConvert.DeserializeObject(strRawJson).ToJson(); } } }