System.Web.NullPointerException

在.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         }
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息