• 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         }
  • 相关阅读:
    纪念--
    【csp模拟赛1】铁路网络 (network.cpp)
    【csp模拟赛1】不服来战 (challenge.cpp)
    【csp模拟赛1】T1 心有灵犀
    【luoguP3959 宝藏】-状压DP
    透彻网络流-wfx-最大流
    【luogu2668斗地主】模拟
    【hdu4734】F(x)-数位DP
    【8.27-模拟赛】remove
    清北学堂-济南游记
  • 原文地址:https://www.cnblogs.com/netlws/p/11059207.html
Copyright © 2020-2023  润新知