前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >System.Web.NullPointerException

System.Web.NullPointerException

作者头像
指尖改变世界
发布2019-06-21 13:04:08
5600
发布2019-06-21 13:04:08
举报
文章被收录于专栏:vuevue

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

示例代码:

代码语言:javascript
复制
1 System.Web.HttpRuntime.Cache.Insert("context", System.Web.HttpContext.Current); //异步调用,HttpContext存入缓存线程共享
2 wait Task.Run(() =>{  })

工具类方法示例代码:

代码语言:javascript
复制
 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         }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-06-20 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 示例代码:
  • 工具类方法示例代码:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档