HttpContextExtension.cs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. using System.Security.Claims;
  2. using System.Text;
  3. using System.Text.RegularExpressions;
  4. using Base;
  5. using Extensions;
  6. using IPTools.Core;
  7. using Model.Base;
  8. using UAParser;
  9. using Util;
  10. namespace Extensions
  11. {
  12. /// <summary>
  13. /// HttpContext扩展类
  14. /// </summary>
  15. public static partial class HttpContextExtension
  16. {
  17. /// <summary>
  18. /// 是否是ajax请求
  19. /// </summary>
  20. /// <param name="request"></param>
  21. /// <returns></returns>
  22. public static bool IsAjaxRequest(this HttpRequest request)
  23. {
  24. if (request == null)
  25. {
  26. throw new ArgumentNullException(nameof(request));
  27. }
  28. //return request.Headers.ContainsKey("X-Requested-With") &&
  29. // request.Headers["X-Requested-With"].Equals("XMLHttpRequest");
  30. return request.Headers["X-Requested-With"] == "XMLHttpRequest" || request.Headers != null && request.Headers["X-Requested-With"] == "XMLHttpRequest";
  31. }
  32. /// <summary>
  33. /// 获取客户端IP
  34. /// </summary>
  35. /// <param name="context"></param>
  36. /// <returns></returns>
  37. public static string GetClientUserIp(this HttpContext context)
  38. {
  39. if (context == null) return "";
  40. var result = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
  41. if (string.IsNullOrEmpty(result))
  42. {
  43. result = context.Connection.RemoteIpAddress?.ToString();
  44. }
  45. if (string.IsNullOrEmpty(result))
  46. throw new Exception("获取IP失败");
  47. if (result.Contains("::1"))
  48. result = "127.0.0.1";
  49. result = result.Replace("::ffff:", "");
  50. result = result.Split(':')?.FirstOrDefault() ?? "127.0.0.1";
  51. result = IsIP(result) ? result : "127.0.0.1";
  52. return result;
  53. }
  54. /// <summary>
  55. /// 判断是否IP
  56. /// </summary>
  57. /// <param name="ip"></param>
  58. /// <returns></returns>
  59. public static bool IsIP(string ip)
  60. {
  61. return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
  62. }
  63. /// <summary>
  64. /// 获取登录用户id
  65. /// </summary>
  66. /// <param name="context"></param>
  67. /// <returns></returns>
  68. public static long GetUId(this HttpContext context)
  69. {
  70. TokenModel loginUser = JwtUtil.GetLoginUser(context);
  71. return loginUser.userId;
  72. // var uid = context.User.FindFirstValue(ClaimTypes.PrimarySid);
  73. // return !string.IsNullOrEmpty(uid) ? long.Parse(uid) : 0;
  74. }
  75. /// <summary>
  76. /// 获取部门id
  77. /// </summary>
  78. /// <param name="context"></param>
  79. /// <returns></returns>
  80. public static long GetDeptId(this HttpContext context)
  81. {
  82. var deptId = context.User.FindFirstValue(ClaimTypes.GroupSid);
  83. return !string.IsNullOrEmpty(deptId) ? long.Parse(deptId) : 0;
  84. }
  85. /// <summary>
  86. /// 获取登录用户名
  87. /// </summary>
  88. /// <param name="context"></param>
  89. /// <returns></returns>
  90. public static string GetName(this HttpContext context)
  91. {
  92. var uid = context.User?.Identity?.Name;
  93. return uid;
  94. }
  95. /// <summary>
  96. /// 判断是否是管理员
  97. /// </summary>
  98. /// <param name="context"></param>
  99. /// <returns></returns>
  100. public static bool IsAdmin(this HttpContext context)
  101. {
  102. var userName = context.GetName();
  103. return userName == GlobalConstant.AdminRole;
  104. }
  105. /// <summary>
  106. /// ClaimsIdentity
  107. /// </summary>
  108. /// <param name="context"></param>
  109. /// <returns></returns>
  110. public static IEnumerable<ClaimsIdentity> GetClaims(this HttpContext context)
  111. {
  112. return context.User?.Identities;
  113. }
  114. //public static int GetRole(this HttpContext context)
  115. //{
  116. // var roleid = context.User.FindFirstValue(ClaimTypes.Role) ?? "0";
  117. // return int.Parse(roleid);
  118. //}
  119. public static string GetUserAgent(this HttpContext context)
  120. {
  121. return context.Request.Headers["User-Agent"];
  122. }
  123. /// <summary>
  124. /// 获取请求令牌
  125. /// </summary>
  126. /// <param name="context"></param>
  127. /// <returns></returns>
  128. public static string GetToken(this HttpContext context)
  129. {
  130. return context.Request.Headers["Authorization"];
  131. }
  132. /// <summary>
  133. /// 获取请求Url
  134. /// </summary>
  135. /// <param name="context"></param>
  136. /// <returns></returns>
  137. public static string GetRequestUrl(this HttpContext context)
  138. {
  139. return context != null ? context.Request.Path.Value : "";
  140. }
  141. /// <summary>
  142. /// 获取请求参数
  143. /// </summary>
  144. /// <param name="context"></param>
  145. /// <returns></returns>
  146. public static string GetQueryString(this HttpContext context)
  147. {
  148. return context != null ? context.Request.QueryString.Value : "";
  149. }
  150. /// <summary>
  151. /// 获取body请求参数
  152. /// </summary>
  153. /// <param name="context"></param>
  154. /// <returns></returns>
  155. public static string GetBody(this HttpContext context)
  156. {
  157. context.Request.EnableBuffering();
  158. //context.Request.Body.Seek(0, SeekOrigin.Begin);
  159. //using var reader = new StreamReader(context.Request.Body, Encoding.UTF8);
  160. ////需要使用异步方式才能获取
  161. //return reader.ReadToEndAsync().Result;
  162. string body = string.Empty;
  163. var buffer = new MemoryStream();
  164. context.Request.Body.Seek(0, SeekOrigin.Begin);
  165. context.Request.Body.CopyToAsync(buffer);
  166. buffer.Position = 0;
  167. try
  168. {
  169. using StreamReader streamReader = new(buffer, Encoding.UTF8);
  170. body = streamReader.ReadToEndAsync().Result;
  171. }
  172. finally
  173. {
  174. buffer?.Dispose();
  175. }
  176. return body;
  177. }
  178. /// <summary>
  179. /// 获取浏览器信息
  180. /// </summary>
  181. /// <param name="context"></param>
  182. /// <returns></returns>
  183. public static ClientInfo GetClientInfo(this HttpContext context)
  184. {
  185. var str = context.GetUserAgent();
  186. var uaParser = Parser.GetDefault();
  187. ClientInfo c = uaParser.Parse(str);
  188. return c;
  189. }
  190. /// <summary>
  191. /// 根据IP获取地理位置
  192. /// </summary>
  193. /// <returns></returns>
  194. public static string GetIpInfo(string IP)
  195. {
  196. var ipInfo = IpTool.Search(IP);
  197. return ipInfo?.Province + "-" + ipInfo?.City + "-" + ipInfo?.NetworkOperator;
  198. }
  199. /// <summary>
  200. /// 设置请求参数
  201. /// </summary>
  202. /// <param name="reqMethod"></param>
  203. /// <param name="context"></param>
  204. public static string GetRequestValue(this HttpContext context, string reqMethod)
  205. {
  206. string param = string.Empty;
  207. if (HttpMethods.IsPost(reqMethod) || HttpMethods.IsPut(reqMethod) || HttpMethods.IsDelete(reqMethod))
  208. {
  209. param = context.GetBody();
  210. string regex = "(?<=\"password\":\")[^\",]*";
  211. param = Regex.Replace(param, regex, "***");
  212. }
  213. if (param.IsEmpty())
  214. {
  215. param = context.GetQueryString();
  216. }
  217. return param;
  218. }
  219. }
  220. }