在.Net异步webApi中咱们须要记录日志信息,须要获取客户端的ip地址,咱们须要使用:HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];来获取客户端的ip地址,在调用异步方法(wait Task.Run(() =>{ }))前须要将主线程中获取的HttpContext.Current对象存至缓存(Cache)中达到多线程共享的目的。若是不是经过主线程获取HttpContext.Current对象将会报空指针异常(NullPointerException)。web
1 System.Web.HttpRuntime.Cache.Insert("context", System.Web.HttpContext.Current); //异步调用,HttpContext存入缓存线程共享 2 wait Task.Run(() =>{ });
1 /// <summary> 2 /// 获取客户端IP地址(无视代理) 3 /// </summary> 4 /// <returns>若失败则返回回送地址</returns> 5 public static string GetHostAddress() 6 { 7 8 HttpContext httpContext = HttpContext.Current; 9 if (httpContext == null) 10 httpContext = HttpRuntime.Cache.Get("context") as HttpContext; 11 string userHostAddress = httpContext.Request.ServerVariables["REMOTE_ADDR"]; 12 13 if (string.IsNullOrEmpty(userHostAddress)) 14 { 15 if (httpContext.Request.ServerVariables["HTTP_VIA"] != null) 16 userHostAddress = httpContext.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString().Split(',')[0].Trim(); 17 } 18 if (string.IsNullOrEmpty(userHostAddress)) 19 { 20 userHostAddress = httpContext.Request.UserHostAddress; 21 } 22 23 //最后判断获取是否成功,并检查IP地址的格式(检查其格式很是重要) 24 if (!string.IsNullOrEmpty(userHostAddress) && IsIP(userHostAddress)) 25 { 26 return userHostAddress; 27 } 28 return "127.0.0.1"; 29 }