隐藏

.net core webapi 后台获取客户端ip地址

发布:2022/10/18 17:58:23作者:管理员 来源:本站 浏览次数:711



1、获取客户端IP地址实现方法(扩展类)

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.Collections.Generic;
using System.Linq;

namespace WebApi.Controllers
{
    /// <summary>
    /// 扩展类
    /// </summary>
    public static class Extension
    {
        /// <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;
        }
    }
}



调用该方法:


var ip = HttpContext.GetClientUserIp();


2、解决Asp.Net Core2.0发布到Ubuntu后不能正确获取客户IP解决办法

/// <summary>
        ///
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        /// <param name="loggerFactory"></param>
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            #region 解决Ubuntu Nginx 代理不能获取IP问题
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });
            #endregion
        }





本人站点用的是Nginx进行代理,而站点指向是本地Ip,不能正确获得客户的IP,这时就需要通过Nginx获取到的IP传递给站点


Nginx的配置

server {
        listen 80;
         server_name www.xxx.com;
         root /var/www/html;
          index index.html index.htm index.nginx-debian.html;

        location / {
        proxy_pass http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection keep-alive;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}



重启Nginx:


sudo service nginx restart;