在.Net异步webApi中我们需要记录日志信息,需要获取客户端的ip地址,我们需要使用:HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];来获取客户端的ip地址,在调用异步方法(wait Task.Run(() =>{  }))前需要将主线程中获取的HttpContext.Current对象存至缓存(Cache)中达到多线程共享的目的。如果不是通过主线程获取HttpContext.Current对象将会报空指针异常(NullPointerException)。

示例代码:

 System.Web.HttpRuntime.Cache.Insert("context", System.Web.HttpContext.Current); //异步调用,HttpContext存入缓存线程共享
wait Task.Run(() =>{ });

工具类方法示例代码:

         /// <summary>
/// 获取客户端IP地址(无视代理)
/// </summary>
/// <returns>若失败则返回回送地址</returns>
public static string GetHostAddress()
{ HttpContext httpContext = HttpContext.Current;
if (httpContext == null)
httpContext = HttpRuntime.Cache.Get("context") as HttpContext;
string userHostAddress = httpContext.Request.ServerVariables["REMOTE_ADDR"]; if (string.IsNullOrEmpty(userHostAddress))
{
if (httpContext.Request.ServerVariables["HTTP_VIA"] != null)
userHostAddress = httpContext.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString().Split(',')[].Trim();
}
if (string.IsNullOrEmpty(userHostAddress))
{
userHostAddress = httpContext.Request.UserHostAddress;
} //最后判断获取是否成功,并检查IP地址的格式(检查其格式非常重要)
if (!string.IsNullOrEmpty(userHostAddress) && IsIP(userHostAddress))
{
return userHostAddress;
}
return "127.0.0.1";
}

最新文章

  1. jsp页面显示问题
  2. How to stop pycharm show files in project in red color?
  3. SQLServer异步调用,批量复制
  4. IOS开发——01_第一个OC程序
  5. nutz的json视图
  6. Linux内核设计第三周——构造一个简单的Linux系统
  7. 前端AJAX传递数组给Springmvc接收处理
  8. [light oj 1013] Love Calculator
  9. android102 查询,插入联系人
  10. 以字符串形式读取github上.json文件
  11. [Linked List]Sort List
  12. SVN权限解析规则详解(转)
  13. git入门大全
  14. .net开源工作流引擎ccflow表单数据返回值Pop分组模式和表格模式对比
  15. 转载&amp;修改:赶集mysql军规
  16. 网址导航18A
  17. 异常处理汇总 ~ 修正果带着你的Code飞奔吧!
  18. shell编程中如何执行oracle语句
  19. C. Maximum Subrectangle
  20. 雷林鹏分享:C# 常量

热门文章

  1. ServerManager.exe 0xc0000135 应用程序错误
  2. nginx配置自签名https
  3. [技术博客]采用Bootstrap框架进行排版布局
  4. etcd启动报错:couldn&#39;t find local name &quot;default&quot; in the initial cluster configuration
  5. 荔枝派nano例子
  6. Jackson的基本用法与拓展
  7. 复制centos 后不能上网,处理办法
  8. 【HBase】HBase 单机版安装及使用
  9. Pi1-lite
  10. SpringMVC返回值响应