HttpContextExtensions.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using Microsoft.AspNetCore.Http;
  5. using Microsoft.Extensions.Primitives;
  6. namespace TEAMModelOS.SDK.Extension
  7. {
  8. public static class HttpContextExtensions
  9. {
  10. /// <summary>
  11. /// 取得驗證金鑰,Authorization
  12. /// </summary>
  13. public static string GetToken(this HttpContext httpContext)
  14. {
  15. return httpContext.Request.Headers["Authorization"].ToString();
  16. }
  17. /// <summary>
  18. /// 取得JWT驗證金鑰,Authorization Bearer
  19. /// </summary>
  20. /// <param name="httpContext"></param>
  21. /// <returns></returns>
  22. public static string GetJwtToken(this HttpContext httpContext)
  23. {
  24. var token = string.Empty;
  25. string authorization = httpContext.Request.Headers["Authorization"].ToString();
  26. if (!string.IsNullOrWhiteSpace(authorization) && authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
  27. {
  28. token = authorization.Substring("Bearer ".Length).Trim();
  29. }
  30. return token;
  31. }
  32. /// <summary>
  33. /// 取得遠端呼叫的IP
  34. /// </summary>
  35. public static string GetRemoteIP(this HttpContext httpContext)
  36. {
  37. return httpContext?.Connection?.RemoteIpAddress?.ToString();
  38. }
  39. /// <summary>
  40. /// 取得X-Auth-Key值
  41. /// </summary>
  42. /// <param name="key">Key Name</param>
  43. /// <returns></returns>
  44. public static string GetXAuth(this HttpContext httpContext, string key = null)
  45. {
  46. try
  47. {
  48. if (httpContext.Request.Headers.TryGetValue($"X-Auth-{key}", out StringValues value))
  49. return value.ToString();
  50. else
  51. return null;
  52. }
  53. catch
  54. {
  55. return null;
  56. }
  57. }
  58. /// <summary>
  59. /// 取得User-Agent值
  60. /// </summary>
  61. public static string GetUserAgent(this HttpContext httpContext)
  62. {
  63. try
  64. {
  65. return httpContext.Request.Headers["User-Agent"].ToString();
  66. }
  67. catch
  68. {
  69. return null;
  70. }
  71. }
  72. /// <summary>
  73. /// 取得Scheme值
  74. /// </summary>
  75. public static string GetScheme(this HttpContext httpContext)
  76. {
  77. return httpContext?.Request?.Scheme;
  78. }
  79. /// <summary>
  80. /// 取得HostName值
  81. /// </summary>
  82. public static string GetHostName(this HttpContext httpContext)
  83. {
  84. return httpContext?.Request?.Host.ToString();
  85. }
  86. }
  87. }