1 建立类: 2 3 using System; 4 using System.Collections.Generic; 5 using System.Linq; 6 using System.Threading.Tasks; 7 using Microsoft.AspNetCore.Http; 8 9 namespace Iyibank.Core 10 { 11 public static class MyHttpContext 12 { 13 public static IServiceProvider ServiceProvider; 14 15 static MyHttpContext() 16 { } 17 18 19 public static HttpContext Current 20 { 21 get 22 { 23 object factory = ServiceProvider.GetService(typeof(Microsoft.AspNetCore.Http.IHttpContextAccessor)); 24 25 HttpContext context = ((IHttpContextAccessor)factory).HttpContext; 26 return context; 27 } 28 } 29 } 30 } 31 32 Startup.cs添加如下 33 34 public void ConfigureServices(IServiceCollection services)内容下添加如下 35 36 services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>(); 37 38 Configure修改如下 39 40 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,IServiceProvider svp) 41 42 Configure下添加以下内容 43 44 Iyibank.Core.MyHttpContext.ServiceProvider = svp; 45 46 这样在其他地方需要使用时,直接调用即可 47 48 /// <summary> 49 /// 获得当前页面客户端的IP 50 /// </summary> 51 /// <returns>当前页面客户端的IP</returns> 52 public static string GetIP() 53 { 54 //try 55 //{ 56 string result = (MyHttpContext.Current.Request.Headers["HTTP_X_FORWARDED_FOR"].ToString() != null 57 && MyHttpContext.Current.Request.Headers["HTTP_X_FORWARDED_FOR"] != String.Empty) 58 ? MyHttpContext.Current.Request.Headers["HTTP_X_FORWARDED_FOR"] 59 : MyHttpContext.Current.Request.Headers["REMOTE_ADDR"]; 60 // string result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; 61 if (string.IsNullOrEmpty(result)) 62 result = MyHttpContext.Current.Request.Headers["HTTP_X_FORWARDED_FOR"]; 63 64 if (string.IsNullOrEmpty(result) || !Utils.IsIP(result)) 65 return "127.0.0.1"; 66 67 return result; 68 //} 69 //catch 70 //{ 71 // return "127.0.0.1"; 72 //} 73 }