请问如何在ASP中获取客户端IP地址?NET时使用MVC 6。 请求。ServerVariables["REMOTE_ADDR"]无效。
当前回答
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
public string GetClientIPAddress(HttpContext context)
{
string ip = string.Empty;
if (!string.IsNullOrEmpty(context.Request.Headers["X-Forwarded-For"]))
{
ip = context.Request.Headers["X-Forwarded-For"];
}
else
{
ip = context.Request.HttpContext.Features.Get<IHttpConnectionFeature>().RemoteIpAddress.ToString();
}
return ip;
}
你想获取Ip地址;
GetClientIPAddress(HttpContext);
其他回答
您可以使用IHttpConnectionFeature来获取此信息。
var remoteIpAddress = httpContext.GetFeature<IHttpConnectionFeature>()?.RemoteIpAddress;
截至2021年9月- ASP。NET Core (5.x) MVC项目允许我在我的控制器中以这种方式获取IP地址:
Request.HttpContext.Connection.RemoteIpAddress
现在似乎比过去简单多了。
从这个环节,就有了更好的解决方案。
在Startup.cs中,我们需要添加service-
public void ConfigureServices(IServiceCollection services)
{
........
services.AddHttpContextAccessor();
........
}
然后在任何控制器或任何地方,我们都需要像这样通过依赖注入来使用它
private IHttpContextAccessor HttpContextAccessor { get; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IWebHostEnvironment env, IHttpContextAccessor httpContextAccessor)
: base(options)
{
Environment = env;
HttpContextAccessor = httpContextAccessor;
//this.Database.EnsureCreated();
}
然后得到这样的IP
IPAddress userIp = HttpContextAccessor.HttpContext.Connection.RemoteIpAddress;
第一次添加
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" };
}
希望这对你有用
可以添加一些回退逻辑来处理负载均衡器的存在。
此外,通过检查,即使没有负载均衡器,X-Forwarded-For报头也会被设置(可能是因为额外的Kestrel层?):
public string GetRequestIP(bool tryUseXForwardHeader = true)
{
string ip = null;
// todo support new "Forwarded" header (2014) https://en.wikipedia.org/wiki/X-Forwarded-For
// X-Forwarded-For (csv list): Using the First entry in the list seems to work
// for 99% of cases however it has been suggested that a better (although tedious)
// approach might be to read each IP from right to left and use the first public IP.
// http://stackoverflow.com/a/43554000/538763
//
if (tryUseXForwardHeader)
ip = GetHeaderValueAs<string>("X-Forwarded-For").SplitCsv().FirstOrDefault();
// RemoteIpAddress is always null in DNX RC1 Update1 (bug).
if (ip.IsNullOrWhitespace() && _httpContextAccessor.HttpContext?.Connection?.RemoteIpAddress != null)
ip = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
if (ip.IsNullOrWhitespace())
ip = GetHeaderValueAs<string>("REMOTE_ADDR");
// _httpContextAccessor.HttpContext?.Request?.Host this is the local host.
if (ip.IsNullOrWhitespace())
throw new Exception("Unable to determine caller's IP.");
return ip;
}
public T GetHeaderValueAs<T>(string headerName)
{
StringValues values;
if (_httpContextAccessor.HttpContext?.Request?.Headers?.TryGetValue(headerName, out values) ?? false)
{
string rawValues = values.ToString(); // writes out as Csv when there are multiple.
if (!rawValues.IsNullOrWhitespace())
return (T)Convert.ChangeType(values.ToString(), typeof(T));
}
return default(T);
}
public static List<string> SplitCsv(this string csvList, bool nullOrWhitespaceInputReturnsNull = false)
{
if (string.IsNullOrWhiteSpace(csvList))
return nullOrWhitespaceInputReturnsNull ? null : new List<string>();
return csvList
.TrimEnd(',')
.Split(',')
.AsEnumerable<string>()
.Select(s => s.Trim())
.ToList();
}
public static bool IsNullOrWhitespace(this string s)
{
return String.IsNullOrWhiteSpace(s);
}
假设_httpContextAccessor通过DI提供。