请问如何在ASP中获取客户端IP地址?NET时使用MVC 6。 请求。ServerVariables["REMOTE_ADDR"]无效。
当前回答
在IIS上使用负载均衡器运行。net core(3.1.4)不能与其他建议的解决方案一起工作。
手动读取X-Forwarded-For报头可以。 这段代码假设这个报头包含一个IP。
IPAddress ip;
var headers = Request.Headers.ToList();
if (headers.Exists((kvp) => kvp.Key == "X-Forwarded-For"))
{
// when running behind a load balancer you can expect this header
var header = headers.First((kvp) => kvp.Key == "X-Forwarded-For").Value.ToString();
// in case the IP contains a port, remove ':' and everything after
ip = IPAddress.Parse(header.Remove(header.IndexOf(':')));
}
else
{
// this will always have a value (running locally in development won't have the header)
ip = Request.HttpContext.Connection.RemoteIpAddress;
}
感谢@JawadAlShaikh和@BozoJoe指出IP可以包含一个端口,x - forward - for可以包含多个IP。
其他回答
在项目。Json添加一个依赖:
"Microsoft.AspNetCore.HttpOverrides": "2.2.0"
在Startup.cs中,在Configure()方法中添加:
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor |
ForwardedHeaders.XForwardedProto
});
当然,还有:
using Microsoft.AspNetCore.HttpOverrides;
然后,我可以通过使用:
Request.HttpContext.Connection.RemoteIpAddress
在我的情况下,在VS中调试时,我总是得到IpV6 localhost,但在IIS上部署时,我总是得到远程IP。
一些有用的链接: 如何在ASP中获取客户端IP地址。网络核心?RemoteIpAddress为空
::1可能是因为:
连接终止在IIS,然后转发到Kestrel, v.next web服务器,因此连接到web服务器确实是从本地主机。(https://stackoverflow.com/a/35442401/5326387)
编辑12/2020:感谢SolidSnake:截至2020年12月,最新版本是2.2.0
Edit 06/2021:感谢Hakan fakhtik:在。net 5中,命名空间是Microsoft.AspNetCore.Builder
您可以使用IHttpConnectionFeature来获取此信息。
var remoteIpAddress = httpContext.GetFeature<IHttpConnectionFeature>()?.RemoteIpAddress;
试试这个:
string remoteHost = $"{httpContext.Connection.RemoteIpAddress}:{httpContext.Connection.RemotePort}";
根据官方文档,如果你使用Apache或Nginx集成,以下代码应该添加到启动。ConfigureServices方法。
// using Microsoft.AspNetCore.HttpOverrides;
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor |
ForwardedHeaders.XForwardedProto;
// Only loopback proxies are allowed by default.
// Clear that restriction because forwarders are enabled by explicit
// configuration.
options.KnownNetworks.Clear();
options.KnownProxies.Clear();
});
最重要的是,在配置方法中使用
app.UseForwardedHeaders();
进一步假设在nginx conf文件中,在一个位置内,使用
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
现在X-Forwarded-For中的第一个条目将是真正的客户端IP。
重要:如果你想保护应用程序,不允许攻击者注入x - forward - for,请阅读这个答案。
请参见转发Linux和非iis反向代理方案、配置Nginx和处理无效报头
第一次添加
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" };
}
希望这对你有用
推荐文章
- 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”的服务