第一步:先写一个 根据Ip获取我们所要的信息的方法
public static string GetstringIpAddress(string strIp)
{
string html = string.Empty;
using (WebClient MyWebClient = new WebClient())
{
//控制台应用和.net core 需要这一句,需要安装NetGet包System.Text.Encoding.CodePages
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Encoding encode = Encoding.GetEncoding("gb2312");
MyWebClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36");
MyWebClient.Credentials = CredentialCache.DefaultCredentials;
Byte[] pageData = MyWebClient.DownloadData("https://www.ip138.com/iplookup.asp?ip=" + strIp + "&action=2");
html = encode.GetString(pageData);
}
string pre = "var ip_result = {\"ASN归属地\":\"";
int pos = html.IndexOf(pre);
html = html.Substring(pos + pre.Length);
html = html.Substring(0, html.IndexOf('"'));
string[] res = html.Split(new char[] { '省', '市', ' ' }, StringSplitOptions.RemoveEmptyEntries);
return res[1];
}
//因为我需要的是城市,所以在此方法中我就返回了城市,大家如果需要其他的可以修改 res[数字] 进行获取
第二步:在接口中调用这个方法即可
//这样就获取到我们想要的城市了