zoukankan      html  css  js  c++  java
  • .netcore 获取请求客户端IP

      

          /// <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地址的格式(检查其格式非常重要)
                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]?dd?).){3}(2[0-4]d|25[0-5]|[01]?dd?)$");
            }

      在startup.cs中Configure方法,添加如下:

           #region 解决Ubuntu Nginx 代理不能获取IP问题
                app.UseForwardedHeaders(new ForwardedHeadersOptions
                {
                    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
                });
                #endregion

      调用方法:

            [HttpPost("publish")]
            public WebApiResult TaskPublish(UserInfo request)
            {
    
                string ip =GetClientUserIp(HttpContext.Request.HttpContext);

       

  • 相关阅读:
    新东西-intel edison
    MFC AfxMessageBox(_T("Please Load Rawdata First !"));
    libgl1-mesa-glx:i386 : 依赖: libglapi-mesa:i386
    开源硬件_瑞芯微开发板
    手机方案商
    嵌入式Linux应用开发__求职要求
    工作要求
    Proc文件系统接口调试
    Sysfs文件系统接口调试
    Ubuntu Linux 解决 bash ./ 没有那个文件或目录 的方法
  • 原文地址:https://www.cnblogs.com/personblog/p/14661627.html
Copyright © 2011-2022 走看看