nginx反向代理后abp的webapi host如何获取客户端ip?
程序员文章站
2022-09-30 18:41:45
nginx反向代理后abp的webapi host如何获取客户端ip ......
dotnet core 跨平台是微软伟大的创举,脱离iis后服务器成本都降低了。
问题
这不,采用abp搞了个小项目,部署到centos后发现审计日志里面的ip信息不对。
解决
这个问题在.net 4.5下处理过,记得当时是继承 webclientinfoprovider重写getclientipaddress。
将代码拿来后发现dotnet core下报错。
跟进后发现 dotnet core下使用的是 abp.aspnetcore.mvc.auditing下的:httpcontextclientinfoprovider
步骤一
修改代码如下,将其放在 xxx.web.core 的extensions目录:
public class webclientinfoproviderfix : iclientinfoprovider { public string browserinfo => getbrowserinfo(); public string clientipaddress => getclientipaddress(); public string computername => getcomputername(); public ilogger logger { get; set; } private readonly ihttpcontextaccessor _httpcontextaccessor; private readonly httpcontext _httpcontext; /// <summary> /// creates a new <see cref="httpcontextclientinfoprovider"/>. /// </summary> public webclientinfoproviderfix(ihttpcontextaccessor httpcontextaccessor) { _httpcontextaccessor = httpcontextaccessor; _httpcontext = httpcontextaccessor.httpcontext; logger = nulllogger.instance; } protected virtual string getbrowserinfo() { var httpcontext = _httpcontextaccessor.httpcontext ?? _httpcontext; return httpcontext?.request?.headers?["user-agent"]; } protected virtual string getclientipaddress() { try { var httpcontext = _httpcontextaccessor.httpcontext ?? _httpcontext; var headers = httpcontext?.request.headers; if (headers!=null&&headers.containskey("x-forwarded-for")) { httpcontext.connection.remoteipaddress = ipaddress.parse(headers["x-forwarded-for"].tostring().split(',', stringsplitoptions.removeemptyentries)[0]); } return httpcontext?.connection?.remoteipaddress?.tostring(); } catch (exception ex) { logger.warn(ex.tostring()); } return null; } protected virtual string getcomputername() { return null; //todo: implement! } }
步骤二
然后xxxwebcoremodule.cs中添加如下:
//jieky@2019-1-24 针对 获取客户端ip异常的处理 configuration.replaceservice(typeof(abp.auditing.iclientinfoprovider), () => { iocmanager.register<abp.auditing.iclientinfoprovider, extensions.webclientinfoproviderfix>(abp.dependency.dependencylifestyle.transient); });
步骤三
nginx配置例子
server { listen 5002; access_log off; 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; } }
参考:
上一篇: ELGamal详解(Java实现)
推荐阅读
-
.Net Core/Framework之Nginx反向代理后获取客户端IP等数据探索
-
nginx反向代理后abp的webapi host如何获取客户端ip?
-
关于.net core使用nginx做反向代理获取客户端ip的问题
-
通过nginx代理后,获取请求URL(getRequestURL)的解决方法,host显示的是本地ip
-
Tomcat获取Nginx反向代理的客户端IP地址
-
PHP、Tomcat获取Nginx代理后的客户端真实IP
-
nginx反向代理后abp的webapi host如何获取客户端ip?
-
.Net Core/Framework之Nginx反向代理后获取客户端IP等数据探索
-
通过nginx反向代理,Tomcat获取真实的客户端IP而非服务器IP nginx tomcat 慢 nginx代理tomcat nginx tomcat 40
-
通过nginx反向代理,Tomcat获取真实的客户端IP而非服务器IP nginx tomcat 慢 nginx代理tomcat nginx tomcat 40