System.Web.NullPointerException

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

示例代码:

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         }

转载于:https://www.cnblogs.com/netlws/p/11059207.html

猜你喜欢

转载自blog.csdn.net/weixin_34160277/article/details/93675896