using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Bowin.Common.Utility { public class HttpHelper { public static IHttpContextAccessor Accessor; public static IWebHostEnvironment WebHostEnvironment { get; set; } public static IServiceCollection ServiceCollection; public static HttpContext Current { get { return Accessor.HttpContext; } } public static T GetService() where T : class { if (Accessor.HttpContext != null) { return Accessor.HttpContext.RequestServices.GetService(); } else { return ServiceCollection.BuildServiceProvider().GetService(); } } public static IEnumerable GetServices() { if (Accessor.HttpContext != null) { return Accessor.HttpContext.RequestServices.GetServices(); } else { return ServiceCollection.BuildServiceProvider().GetServices(); } } public static object GetService(Type serviceType) { if (Accessor.HttpContext != null) { return Accessor.HttpContext.RequestServices.GetService(serviceType); } else { return ServiceCollection.BuildServiceProvider().GetService(serviceType); } } public static IEnumerable GetServices(Type serviceType) { if (Accessor.HttpContext != null) { return Accessor.HttpContext.RequestServices.GetServices(serviceType); } else { return ServiceCollection.BuildServiceProvider().GetServices(serviceType); } } public static string MapPath(string url) { return Path.Combine(WebHostEnvironment.WebRootPath, url.TrimStart("~").Replace('/', Path.DirectorySeparatorChar).TrimStart(Path.DirectorySeparatorChar)); } public static string GetUserIp() { var ip = Current.Request.Headers["X-Forwarded-For"].FirstOrDefault(); if (string.IsNullOrEmpty(ip)) { ip = Current.Connection.RemoteIpAddress.ToString(); } return ip; } } }