我正在 asp.net core mvc 中编写一个 Web 应用程序,我需要找到当前位置 - 至少在城市级别,我该怎么做?有我可以安装的 Nuget 软件包吗?因为支持此功能的.net库仅在.net框架中
您可以使用像 ip-api.com 这样的服务。
这里是通过 ip 地址检索用户位置数据的文档,其中包含 json 响应: https://ip-api.com/docs/api:json
只需在控制器中获取用户的 ip 地址,如此处所示,并使用用户 ip 调用他们的 api。 前任。 http://ip-api.com/json/24.48.0.1
在
Program.cs
中添加这一行来注册IHttpContextAccessor
builder.Services.AddHttpContextAccessor();
使用API
[HttpGet(Name = "EndPointName")]
public async Task<IActionResult> Index()
{
string userIp = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
string apiUrl = $"http://ip-api.com/json/{userIp}";
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(apiUrl);
if (response.IsSuccessStatusCode)
{
string jsonResult = await response.Content.ReadAsStringAsync();
// Process the JSON result
return Ok(jsonResult);
}
}
return BadRequest();
}
如果您使用MVC,您需要添加一个
.cshtml
页面
然后更改行:
return Ok(jsonResult);
至 return View(jsonResult);
或者处理 JSON 结果并返回适合您的应用程序的数据