HttpHelper.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using Microsoft.AspNetCore.Hosting;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.Extensions.DependencyInjection;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Text;
  9. namespace Bowin.Common.Utility
  10. {
  11. public class HttpHelper
  12. {
  13. public static IHttpContextAccessor Accessor;
  14. public static IWebHostEnvironment WebHostEnvironment { get; set; }
  15. public static IServiceCollection ServiceCollection;
  16. public static HttpContext Current
  17. {
  18. get
  19. {
  20. return Accessor.HttpContext;
  21. }
  22. }
  23. public static T GetService<T>() where T : class
  24. {
  25. if (Accessor.HttpContext != null)
  26. {
  27. return Accessor.HttpContext.RequestServices.GetService<T>();
  28. }
  29. else
  30. {
  31. return ServiceCollection.BuildServiceProvider().GetService<T>();
  32. }
  33. }
  34. public static IEnumerable<T> GetServices<T>()
  35. {
  36. if (Accessor.HttpContext != null)
  37. {
  38. return Accessor.HttpContext.RequestServices.GetServices<T>();
  39. }
  40. else
  41. {
  42. return ServiceCollection.BuildServiceProvider().GetServices<T>();
  43. }
  44. }
  45. public static object GetService(Type serviceType)
  46. {
  47. if (Accessor.HttpContext != null)
  48. {
  49. return Accessor.HttpContext.RequestServices.GetService(serviceType);
  50. }
  51. else
  52. {
  53. return ServiceCollection.BuildServiceProvider().GetService(serviceType);
  54. }
  55. }
  56. public static IEnumerable<object> GetServices(Type serviceType)
  57. {
  58. if (Accessor.HttpContext != null)
  59. {
  60. return Accessor.HttpContext.RequestServices.GetServices(serviceType);
  61. }
  62. else
  63. {
  64. return ServiceCollection.BuildServiceProvider().GetServices(serviceType);
  65. }
  66. }
  67. public static string MapPath(string url)
  68. {
  69. return Path.Combine(WebHostEnvironment.WebRootPath, url.TrimStart("~").Replace('/', Path.DirectorySeparatorChar).TrimStart(Path.DirectorySeparatorChar));
  70. }
  71. public static string GetUserIp()
  72. {
  73. var ip = Current.Request.Headers["X-Forwarded-For"].FirstOrDefault();
  74. if (string.IsNullOrEmpty(ip))
  75. {
  76. ip = Current.Connection.RemoteIpAddress.ToString();
  77. }
  78. return ip;
  79. }
  80. }
  81. }