Asp.Net Core2.0获取客户IP地址,及解决发布到Ubuntu服务器获取不到正确IP解决办法
1、获取客户端IP地址实现方法(扩展类)
1 using Microsoft.AspNetCore.Http; 2 using Microsoft.AspNetCore.Mvc.ModelBinding; 3 using System.Collections.Generic; 4 using System.Linq; 5 6 namespace WebApi.Controllers 7 { 8 /// <summary> 9 /// 扩展类 10 /// </summary> 11 public static class Extension 12 { 13 /// <summary> 14 /// 获取客户Ip 15 /// </summary> 16 /// <param name="context"></param> 17 /// <returns></returns> 18 public static string GetClientUserIp(this HttpContext context) 19 { 20 var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault(); 21 if (string.IsNullOrEmpty(ip)) 22 { 23 ip = context.Connection.RemoteIpAddress.ToString(); 24 } 25 return ip; 26 } 27 } 28 }
调用该方法:
var ip = HttpContext.GetClientUserIp();
2、解决Asp.Net Core2.0发布到Ubuntu后不能正确获取客户IP解决办法
1 /// <summary> 2 /// 3 /// </summary> 4 /// <param name="app"></param> 5 /// <param name="env"></param> 6 /// <param name="loggerFactory"></param> 7 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 8 { 9 #region 解决Ubuntu Nginx 代理不能获取IP问题 10 app.UseForwardedHeaders(new ForwardedHeadersOptions 11 { 12 ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto 13 }); 14 #endregion 15 }
本人站点用的是Nginx进行代理,而站点指向是本地Ip,不能正确获得客户的IP,这时就需要通过Nginx获取到的IP传递给站点
Nginx的配置
1 server { 2 listen 80; 3 server_name www.xxx.com; 4 root /var/www/html; 5 index index.html index.htm index.nginx-debian.html; 6 7 location / { 8 proxy_pass http://localhost:5000; 9 proxy_http_version 1.1; 10 proxy_set_header Upgrade $http_upgrade; 11 proxy_set_header Connection keep-alive; 12 proxy_set_header Host $host; 13 proxy_set_header X-Real-IP $remote_addr; 14 proxy_cache_bypass $http_upgrade; 15 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 16 } 17 }
重启Nginx:
sudo service nginx restart;
转载