获取ip地址

1注册服务

 services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

2控制器依赖注入

 private readonly IHttpContextAccessor _accessor;

        public ApiController( IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }

3方法内使用

string spbillCreateIP = _accessor.HttpContext.Connection.RemoteIpAddress.ToString();

 经过测试,获取的的内网的ip地址,我需要的是外网,所有还要改进一下

        /// <summary>
        /// 获取客户端ip
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string GetClientUserIp(this HttpContext context)
        {
            var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (string.IsNullOrEmpty(ip))
            {
                ip = context.Connection.RemoteIpAddress.ToString();
            }
            return ip;
        }

在控制器调用

 string ip = HttpContext.GetClientUserIp();

 

posted @ 2020-08-08 21:59  青兰柳  阅读(272)  评论(0编辑  收藏  举报