• NetCore VUE 前后端分离获取IP


    由于前后端分离项目,前端项目使用nginx部署,并且做了本机代理转发,访问服务地址配置均为localhost(项目都在同一服务器上),如下图:

     

     导致获取的IP地址均为127.0.0.1等本机IP,修改nginx配置文件,如下:

    location / {
            proxy_pass http://localhost:5000;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

    cmd管理员身份进入nginx目录,停止nginx,命令如下:

    D:\nginx-1.21.5>nginx -s stop

    重启nginx:

    D:\nginx-1.21.5>start nginx

    有时候nginx停止命令不能停止nginx,请使用资源管理器杀死进程(您有更好的方法可以留言给我,谢谢)。

    写一个通用方法获取IP,代码如下:

    1. ///
    2. /// 获取客户Ip
    3. ///
    4. ///
    5. ///
    6. static public string fnGetClientUserIp()
    7. {
    8. try
    9. {
    10. var userHostAddress = context.Request.Headers["X-Real-IP"].ToString();
    11. if (string.IsNullOrWhiteSpace(userHostAddress))
    12. {
    13. userHostAddress = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
    14. }
    15. if (string.IsNullOrWhiteSpace(userHostAddress))
    16. {
    17. userHostAddress = context.Connection.RemoteIpAddress.MapToIPv4()?.ToString();
    18. }
    19. if (string.IsNullOrWhiteSpace(userHostAddress))
    20. {
    21. userHostAddress = context.Connection.RemoteIpAddress.ToString();//这个是直接IP,如果经过反向代理IP会变成代理机的,如果代理机就是本机就会变成127.0.0.1
    22. }
    23. if (!string.IsNullOrWhiteSpace(userHostAddress))
    24. {
    25. return userHostAddress;
    26. }
    27. return "127.0.0.1";
    28. }
    29. catch(Exception ex)
    30. {
    31. return ":1";
    32. }
    33. }

    示例:

    string sIp = this.HttpContext.fnGetClientUserIp();

    我的方法封装为HttpContext的扩展方法,修改方法名,代码如下:

    ///


    /// 获取客户Ip
    ///

    ///
    ///

    static public string fnGetClientUserIp(this HttpContext context)

    如果上面代码段你定义为一个类内静态方法,调用方式如下:

    string sIp = 你的Class类名.fnGetClientUserIp();

  • 相关阅读:
    定时执行专家 - 循环触发的危险操作,例如:电脑循环关机、循环重启、循环注销等,请谨慎尝试
    CSAPP Attack Lab
    详解析构函数、拷贝构造函数
    【十四】记一次MySQL宕机恢复过程,MySQL INNODB 损坏恢复
    windows 调用 static lib
    SpringBoot笔记之SpringSecurity
    短视频矩阵系统软件源码
    企业应用级自动化运维的建设思路
    Java-GUI-事件监听
    Java 某个经纬度是否在genjson文件中
  • 原文地址:https://blog.csdn.net/hefeng_aspnet/article/details/126016838