.netcore获取IP地址,Nginx作为反向代理的情况下
作者:互联网
第一步:增加nginx代理http头
server {
listen 80;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://localhost:5000; }
}
第二步:core项目中增加获取IP地址的帮助类
public static class GetHostIP
{
/// <summary>
/// 获取客户Ip
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public static string GetClientUserIp(this HttpContext context)
{
var userHostAddress = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
if (string.IsNullOrEmpty(userHostAddress))
{
userHostAddress = context.Connection.RemoteIpAddress.ToString();//这个是直接IP,如果经过反向代理IP会变成代理机的,如果代理机就是本机就会变成127.0.0.1
}
//最后判断获取是否成功,并检查IP地址的格式
if (!string.IsNullOrEmpty(userHostAddress) && IsIP(userHostAddress))
{
return userHostAddress;
}
return "127.0.0.1";
}
/// <summary>
/// 检查IP地址格式
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
public static bool IsIP(string ip)
{
return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
}
}
补充说明
HttpContext 对象
1.在Mvc 控制器实例中包含了上下文对象,可以直接使用
2.使用IHttpContextAccessor接口获取HttpContext对象
2.1我们先要将它注册到ServiceCollection中,否则无法获取到这个对象。
public void ConfigureServices(IServiceCollection services) {
//services.AddHttpContextAccessor(); services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>(); }
2.2使用时,可以使用构造函数注入的方式获取到这个对象
2.3使用时,手动获取对象
public class TestClass { public static IServiceProvider ServiceProvider; public static HttpContext GetContext() { object factory = ServiceProvider.GetService(typeof(Microsoft.AspNetCore.Http.IHttpContextAccessor)); HttpContext context = ((IHttpContextAccessor)factory).HttpContext; return context; } }
标签:context,netcore,Nginx,static,proxy,userHostAddress,IP地址,HttpContext,public 来源: https://www.cnblogs.com/zhaoweb/p/16080535.html