using Microsoft.AspNetCore.Http;
using System.Text;
using Newtonsoft.Json;
using Furion.HttpRemote;
namespace Easy.Core;
public static class HttpContextExtension
{
///
/// 获取ip
///
///
///
public static string GetRemoteIp(this HttpContext context)
{
string ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
if (string.IsNullOrWhiteSpace(ip))
{
ip = context.GetRemoteIpAddressToIPv4();
}
return ip;
}
///
/// 获取Ip所属详细地理位置
///
///
///
public static string GetGeolocation(this HttpContext context)
{
try
{
string ip = context.GetRemoteIp();
//获取ip信息
return GetGeolocation(ip);
}
catch (Exception e)
{
return string.Empty;
}
}
///
/// 获取ip详细信息
///
///
///
public static string GetGeolocation(string ip)
{
if (string.IsNullOrWhiteSpace(ip))
{
return string.Empty;
}
try
{
var httpRemoteService = App.GetRequiredService();
//获取ip信息
byte[] bytes = httpRemoteService.GetAsByteArray($"http://whois.pconline.com.cn/ipJson.jsp?ip={ip}&json=true");
string json = Encoding.GetEncoding("gb2312").GetString(bytes);
return JsonConvert.DeserializeObject(json)?.Address ?? "";
}
catch
{
return string.Empty;
}
}
}
public class IpInfoDto
{
///
/// ip
///
[JsonProperty("ip")]
public string Ip { get; set; }
///
/// 省份
///
[JsonProperty("pro")]
public string Province { get; set; }
///
/// 省编码
///
[JsonProperty("proCode")]
public string ProCode { get; set; }
///
/// 城市
///
[JsonProperty("city")]
public string City { get; set; }
///
/// 城市编码
///
[JsonProperty("cityCode")]
public string CityCode { get; set; }
///
/// 区域
///
[JsonProperty("region")]
public string Region { get; set; }
///
/// 区编码
///
[JsonProperty("regionCode")]
public string RegionCode { get; set; }
///
/// IP归属地
///
[JsonProperty("addr")]
public string Address { get; set; }
///
///
///
[JsonProperty("regionNames")]
public string RegionNames { get; set; }
///
/// 错误信息
///
[JsonProperty("err")]
public string Error { get; set; }
}