Exemplo n.º 1
0
        /// <summary>
        /// 根据Ip解析地址(淘宝)
        /// </summary>
        /// <returns></returns>
        public async static Task <Ip2AddressEntity> AnalysisIp2AddressAsync(string ip)
        {
            Ip2AddressEntity ip2AddressEntity = new Ip2AddressEntity();
            var getIpInfoUrl = QueryHelpers.AddQueryString("http://ip.taobao.com/service/getIpInfo.php", "ip", ip);

            try
            {
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.ParseAdd("application/json");
                    client.Timeout = TimeSpan.FromSeconds(120);
                    client.MaxResponseContentBufferSize = 1024 * 1024 * 10; // 10 MB

                    var response = await client.GetStringAsync(getIpInfoUrl);

                    //response.EnsureSuccessStatusCode();

                    //var returnResultString = await response.Content.ReadAsStringAsync();
                    var deserializeResult = JsonConvert.DeserializeObject <RequestAnalysisDataResult>(response);

                    if (deserializeResult.Code == 0)
                    {
                        ip2AddressEntity = JsonConvert.DeserializeObject <Ip2AddressEntity>(response);
                    }
                    else
                    {
                        ip2AddressEntity.Code = deserializeResult.Code;
                    }
                }
            }
            catch (WebException webEx)
            {
                //log it
                string logDebug = $"获取客户端IP地址出错. {ip},{webEx.Status},{webEx.Message},{webEx.StackTrace},{webEx.Source}";
                return(null);
            }

            ReplaceSuffix(ip2AddressEntity);

            return(ip2AddressEntity);
        }
Exemplo n.º 2
0
 public static void ReplaceSuffix(Ip2AddressEntity ip2AddressEntity)
 {
     ip2AddressEntity.AddressData.Region = ip2AddressEntity.AddressData.Region.Replace("省", "");
     ip2AddressEntity.AddressData.Region = ip2AddressEntity.AddressData.Region.Replace("市", "");
 }