HttpContextExtensions.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Threading;
  8. using Microsoft.AspNetCore.Http;
  9. using Microsoft.AspNetCore.Mvc.Controllers;
  10. using Microsoft.Extensions.Primitives;
  11. namespace TEAMModelOS.SDK.Extension
  12. {
  13. public static class HttpContextExtensions
  14. {
  15. /// <summary>
  16. /// 取得驗證金鑰,Authorization
  17. /// </summary>
  18. public static string GetToken(this HttpContext httpContext)
  19. {
  20. return httpContext.Request.Headers["Authorization"].ToString();
  21. }
  22. /// <summary>
  23. /// 获取 Action 特性
  24. /// </summary>
  25. /// <typeparam name="TAttribute"></typeparam>
  26. /// <param name="httpContext"></param>
  27. /// <returns></returns>
  28. public static TAttribute GetMetadata<TAttribute>(this HttpContext httpContext)
  29. where TAttribute : class
  30. {
  31. return httpContext.GetEndpoint()?.Metadata?.GetMetadata<TAttribute>();
  32. }
  33. /// <summary>
  34. /// 获取 控制器/Action 描述器
  35. /// </summary>
  36. /// <param name="httpContext"></param>
  37. /// <returns></returns>
  38. public static ControllerActionDescriptor GetControllerActionDescriptor(this HttpContext httpContext)
  39. {
  40. return httpContext.GetEndpoint()?.Metadata?.FirstOrDefault(u => u is ControllerActionDescriptor) as ControllerActionDescriptor;
  41. }
  42. /// <summary>
  43. /// 获取本机 IPv4地址
  44. /// </summary>
  45. /// <param name="context"></param>
  46. /// <returns></returns>
  47. public static string GetLocalIpAddressToIPv4(this HttpContext context)
  48. {
  49. return context.Connection.LocalIpAddress?.MapToIPv4()?.ToString();
  50. }
  51. /// <summary>
  52. /// 获取本机 IPv6地址
  53. /// </summary>
  54. /// <param name="context"></param>
  55. /// <returns></returns>
  56. public static string GetLocalIpAddressToIPv6(this HttpContext context)
  57. {
  58. return context.Connection.LocalIpAddress?.MapToIPv6()?.ToString();
  59. }
  60. /// <summary>
  61. /// 获取远程 IPv4地址
  62. /// </summary>
  63. /// <param name="context"></param>
  64. /// <returns></returns>
  65. public static string GetRemoteIpAddressToIPv4(this HttpContext context)
  66. {
  67. return context.Connection.RemoteIpAddress?.MapToIPv4()?.ToString();
  68. }
  69. /// <summary>
  70. /// 获取远程 IPv6地址
  71. /// </summary>
  72. /// <param name="context"></param>
  73. /// <returns></returns>
  74. public static string GetRemoteIpAddressToIPv6(this HttpContext context)
  75. {
  76. return context.Connection.RemoteIpAddress?.MapToIPv6()?.ToString();
  77. }
  78. /// <summary>
  79. /// 获取完整请求地址
  80. /// </summary>
  81. /// <param name="request"></param>
  82. /// <returns></returns>
  83. public static string GetRequestUrlAddress(this HttpRequest request)
  84. {
  85. return new StringBuilder()
  86. .Append(request.Scheme)
  87. .Append("://")
  88. .Append(request.Host)
  89. .Append(request.PathBase)
  90. .Append(request.Path)
  91. .Append(request.QueryString)
  92. .ToString();
  93. }
  94. /// <summary>
  95. /// 获取来源地址
  96. /// </summary>
  97. /// <param name="request"></param>
  98. /// <param name="refererHeaderKey"></param>
  99. /// <returns></returns>
  100. public static string GetRefererUrlAddress(this HttpRequest request, string refererHeaderKey = "Referer")
  101. {
  102. return request.Headers[refererHeaderKey].ToString();
  103. }
  104. /// <summary>
  105. /// 读取 Body 内容
  106. /// </summary>
  107. /// <param name="httpContext"></param>
  108. /// <remarks>需先在 Startup 的 Configure 中注册 app.EnableBuffering()</remarks>
  109. /// <returns></returns>
  110. public static async Task<string> ReadBodyContentAsync(this HttpContext httpContext)
  111. {
  112. if (httpContext == null) return default;
  113. return await httpContext.Request.ReadBodyContentAsync();
  114. }
  115. /// <summary>
  116. /// 读取 Body 内容
  117. /// </summary>
  118. /// <param name="request"></param>
  119. /// <remarks>需先在 Startup 的 Configure 中注册 app.EnableBuffering()</remarks>
  120. /// <returns></returns>
  121. public static async Task<string> ReadBodyContentAsync(this HttpRequest request)
  122. {
  123. request.Body.Seek(0, SeekOrigin.Begin);
  124. using var reader = new StreamReader(request.Body, Encoding.UTF8, true, 1024, true);
  125. var body = await reader.ReadToEndAsync();
  126. // 回到顶部,解决此类问题 https://gitee.com/dotnetchina/Furion/issues/I6NX9E
  127. request.Body.Seek(0, SeekOrigin.Begin);
  128. return body;
  129. }
  130. /// <summary>
  131. /// 判断是否是 WebSocket 请求
  132. /// </summary>
  133. /// <param name="context"></param>
  134. /// <returns></returns>
  135. public static bool IsWebSocketRequest(this HttpContext context)
  136. {
  137. return context.WebSockets.IsWebSocketRequest || context.Request.Path == "/ws";
  138. }
  139. /// <summary>
  140. /// 设置响应头 Tokens
  141. /// </summary>
  142. /// <param name="httpContext"></param>
  143. /// <param name="accessToken"></param>
  144. /// <param name="refreshToken"></param>
  145. public static void SetTokensOfResponseHeaders(this HttpContext httpContext, string accessToken, string refreshToken = null)
  146. {
  147. httpContext.Response.Headers["access-token"] = accessToken;
  148. if (!string.IsNullOrWhiteSpace(refreshToken))
  149. {
  150. httpContext.Response.Headers["x-access-token"] = refreshToken;
  151. }
  152. }
  153. /// <summary>
  154. /// 取得JWT驗證金鑰,Authorization Bearer
  155. /// </summary>
  156. /// <param name="httpContext"></param>
  157. /// <returns></returns>
  158. public static string GetJwtToken(this HttpContext httpContext)
  159. {
  160. var token = string.Empty;
  161. string authorization = httpContext.Request.Headers["Authorization"].ToString();
  162. if (!string.IsNullOrWhiteSpace(authorization) && authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
  163. {
  164. token = authorization.Substring("Bearer ".Length).Trim();
  165. }
  166. return token;
  167. }
  168. /// <summary>
  169. /// 取得遠端呼叫的IP
  170. /// </summary>
  171. public static string GetRemoteIP(this HttpContext httpContext)
  172. {
  173. return httpContext?.Connection?.RemoteIpAddress?.ToString();
  174. }
  175. /// <summary>
  176. /// 取得X-Auth-Key值
  177. /// </summary>
  178. /// <param name="key">Key Name</param>
  179. /// <returns></returns>
  180. public static string GetXAuth(this HttpContext httpContext, string key = null)
  181. {
  182. try
  183. {
  184. if (httpContext.Request.Headers.TryGetValue($"X-Auth-{key}", out StringValues value))
  185. return value.ToString();
  186. else
  187. return null;
  188. }
  189. catch
  190. {
  191. return null;
  192. }
  193. }
  194. /// <summary>
  195. /// 取得X-Auth-Key值
  196. /// </summary>
  197. /// <param name="key">Key Name</param>
  198. /// <returns></returns>
  199. public static string GetAuthorization(this HttpContext httpContext)
  200. {
  201. try
  202. {
  203. if (httpContext.Request.Headers.TryGetValue("Authorization", out StringValues value))
  204. return value.ToString();
  205. else
  206. return null;
  207. }
  208. catch
  209. {
  210. return null;
  211. }
  212. }
  213. /// <summary>
  214. /// 取得AuthToken權杖資訊
  215. /// </summary>
  216. /// <param name="key">Key Name</param>
  217. /// <returns></returns>
  218. public static (string id, string school) GetApiTokenInfo(this HttpContext httpContext, string key = null)
  219. {
  220. object id = null, school = null;
  221. httpContext?.Items.TryGetValue("ID", out id);
  222. httpContext?.Items.TryGetValue("School", out school);
  223. return (id?.ToString(), school?.ToString());
  224. }
  225. /// <summary>
  226. /// 取得AuthToken權杖資訊
  227. /// </summary>
  228. /// <param name="key">Key Name</param>
  229. /// <returns></returns>
  230. public static (string id, string name, string picture, string school) GetAuthTokenInfo(this HttpContext httpContext, string key = null)
  231. {
  232. object id = null, name = null, picture = null, school = null;
  233. httpContext?.Items.TryGetValue("ID", out id);
  234. httpContext?.Items.TryGetValue("Name", out name);
  235. httpContext?.Items.TryGetValue("Picture", out picture);
  236. httpContext?.Items.TryGetValue("School", out school);
  237. return (id?.ToString(), name?.ToString(), picture?.ToString(), school?.ToString());
  238. }
  239. /// <summary>
  240. /// 取得AuthToken權杖資訊
  241. /// </summary>
  242. /// <param name="key">Key Name</param>
  243. /// <returns></returns>
  244. public static (string id, string name, string picture, string school, string area, string keyData) GetAuthTokenKey(this HttpContext httpContext, string key = null)
  245. {
  246. object id = null, name = null, picture = null, school = null, area = null, keyData = null;
  247. httpContext?.Items.TryGetValue("ID", out id);
  248. httpContext?.Items.TryGetValue("Name", out name);
  249. httpContext?.Items.TryGetValue("Picture", out picture);
  250. httpContext?.Items.TryGetValue("School", out school);
  251. httpContext?.Items.TryGetValue("Area", out area);
  252. if (!string.IsNullOrWhiteSpace(key))
  253. {
  254. httpContext?.Items.TryGetValue(key, out keyData);
  255. }
  256. return (id?.ToString(), name?.ToString(), picture?.ToString(), school?.ToString(), area?.ToString(), keyData?.ToString());
  257. }
  258. /// <summary>
  259. /// 取得User-Agent值
  260. /// </summary>
  261. public static string GetUserAgent(this HttpContext httpContext)
  262. {
  263. try
  264. {
  265. return httpContext.Request.Headers["User-Agent"].ToString();
  266. }
  267. catch
  268. {
  269. return null;
  270. }
  271. }
  272. /// <summary>
  273. /// 取得Scheme值
  274. /// </summary>
  275. public static string GetScheme(this HttpContext httpContext)
  276. {
  277. return httpContext?.Request?.Scheme;
  278. }
  279. /// <summary>
  280. /// 取得HostName值
  281. /// </summary>
  282. public static string GetHostName(this HttpContext httpContext)
  283. {
  284. return httpContext?.Request?.Host.ToString();
  285. }
  286. /// <summary>
  287. /// 设置本地cookie
  288. /// </summary>
  289. /// <param name="key">键</param>
  290. /// <param name="value">值</param>
  291. /// <param name="minutes">过期时长,单位:分钟</param>
  292. public static void SetCookies(HttpResponse Response, string key, string value, int minutes = 30)
  293. {
  294. Response.Cookies.Append(key, value, new CookieOptions
  295. {
  296. Expires = DateTimeOffset.Now.AddMinutes(minutes)
  297. });
  298. }
  299. /// <summary>
  300. /// 删除指定的cookie
  301. /// </summary>
  302. /// <param name="key">键</param>
  303. public static void DeleteCookies(HttpContext httpContext, string key)
  304. {
  305. httpContext.Response.Cookies.Delete(key);
  306. }
  307. }
  308. }