123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- 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<T>() where T : class
- {
-
- if (Accessor.HttpContext != null)
- {
- return Accessor.HttpContext.RequestServices.GetService<T>();
- }
- else
- {
- return ServiceCollection.BuildServiceProvider().GetService<T>();
- }
- }
- public static IEnumerable<T> GetServices<T>()
- {
- if (Accessor.HttpContext != null)
- {
- return Accessor.HttpContext.RequestServices.GetServices<T>();
- }
- else
- {
- return ServiceCollection.BuildServiceProvider().GetServices<T>();
- }
- }
- 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<object> 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;
- }
- }
- }
|