System.Web.NullPointerException

In .Net asynchronous webApi we need to log information, you need to obtain the ip address of the client, we need to use: HttpContext.Current.Request.ServerVariables [ "REMOTE_ADDR"]; to get the ip address of the client, the asynchronous method call (wait Task .Run (() => {})) required before the main thread acquired the object HttpContext.Current memory to the cache (cache) to achieve the purpose of sharing multi-thread. If it is not acquired by the main thread HttpContext.Current objects will report null pointer exception (NullPointerException).

Sample code:

. 1 System.Web.HttpRuntime.Cache.Insert ( " context " , System.Web.HttpContext.Current); // asynchronous calls, HttpContext cached shared thread 
2 the wait Task.Run (() => {});

Tools Method sample code:

. 1          ///  <Summary> 
2          /// Get Client IP address (ignoring agent)
 . 3          ///  </ Summary> 
. 4          ///  <Returns> If the loopback address failed to return </ Returns> 
. 5          public  static  String getHostAddress ()
 . 6          {
 . 7  
. 8              the httpContext = httpContext the HttpContext.Current;
 . 9              IF (httpContext == null )
 10                  httpContext = HttpRuntime.Cache.Get ( " context " ) AS the 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 is                  userHostAddress = httpContext.Request.UserHostAddress;
 21 is              }
 22 is  
23 is              // final judgment acquisition is successful, the IP address and checks the format (check the format is important) 
24              IF (! String .IsNullOrEmpty (userHostAddress) && Isip (userHostAddress))
 25              {
 26 is                  return userHostAddress;
 27              }
 28              return  " 127.0.0.1 " ;
 29          }

 

Reproduced in: https: //www.cnblogs.com/netlws/p/11059207.html

Guess you like

Origin blog.csdn.net/weixin_34160277/article/details/93675896