请问如何在ASP中获取客户端IP地址?NET时使用MVC 6。 请求。ServerVariables["REMOTE_ADDR"]无效。
当前回答
第一次添加
Microsoft.AspNetCore.Http
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
在Startup.cs中的ConfigureServices中 然后在控制器中添加以下代码
private IHttpContextAccessor _accessor;
public LoginController(IHttpContextAccessor accessor)
{
_accessor = accessor;
}
public IEnumerable<string> Get()
{
var ip = _accessor.HttpContext?.Connection?.RemoteIpAddress?.ToString();
return new string[] { ip, "value" };
}
希望这对你有用
其他回答
第一次添加
Microsoft.AspNetCore.Http
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
在Startup.cs中的ConfigureServices中 然后在控制器中添加以下代码
private IHttpContextAccessor _accessor;
public LoginController(IHttpContextAccessor accessor)
{
_accessor = accessor;
}
public IEnumerable<string> Get()
{
var ip = _accessor.HttpContext?.Connection?.RemoteIpAddress?.ToString();
return new string[] { ip, "value" };
}
希望这对你有用
这适用于我(DotNetCore 2.1)
[HttpGet]
public string Get()
{
var remoteIpAddress = HttpContext.Connection.RemoteIpAddress;
return remoteIpAddress.ToString();
}
您还可以使用api.db-ip.com web服务获取IP地址和位置。
这项服务是免费的,但有一个限制:每天1000次请求。
public string GetRemoteIP()
{
HttpClient client = new HttpClient();
var result = client.GetStringAsync("https://api.db-ip.com/v2/free/self").Result;
var ip = JsonSerializer.Deserialize<RemoteIPDto>(result.ToString()).IP;
return ip;
}
public static string GetUserAddress()
{
HttpClient client = new HttpClient();
var result = client.GetStringAsync("https://api.db-ip.com/v2/free/self").Result;
var location = result.ToString();
return remoteAddress;
}
RemoteIPDto类在哪里
public class RemoteIPDto
{
[JsonPropertyName("ipAddress")]
public string IP { get; set; }
[JsonPropertyName("continentCode")]
public string ContinentCode { get; set; }
[JsonPropertyName("continentName")]
public string ContinentName { get; set; }
[JsonPropertyName("countryCode")]
public string CountryCode { get; set; }
[JsonPropertyName("countryName")]
public string CountryName { get; set; }
[JsonPropertyName("city")]
public string City { get; set; }
}
在ASP。NET 2.1,在StartUp.cs中添加此服务:
services.AddHttpContextAccessor();
services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
然后做3步:
在MVC控制器中定义一个变量 private IHttpContextAccessor _accessor DI转换为控制器的构造函数 IHttpContextAccessor访问器 { _accessor = accessor; } 检索IP地址 _accessor.HttpContext.Connection.RemoteIpAddress.ToString ()
事情是这样的。
您可以使用IHttpConnectionFeature来获取此信息。
var remoteIpAddress = httpContext.GetFeature<IHttpConnectionFeature>()?.RemoteIpAddress;
推荐文章
- HTTP POST返回错误:417“期望失败。”
- 如何在。net中创建和使用资源
- 为什么Path。以Path.DirectorySeparatorChar开头的文件名合并不正确?
- 如何在c#中获得正确的时间戳
- Linq选择列表中存在的对象(A,B,C)
- c# .NET中的App.config是什么?如何使用它?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 更好的方法将对象转换为int类型
- 我可以将c#字符串值转换为转义字符串文字吗?
- 在c#中转换char到int
- c#中朋友的对等物是什么?
- 关键字使用virtual+override vs. new
- .NET核心MVC页面更改后不刷新
- 无法解析类型为“Microsoft.AspNetCore.Http.IHttpContextAccessor”的服务