Asp. Net Core2.0 obtains the Client IP address, and solves the problem that the correct IP address cannot be obtained after publishing to the Ubuntu server. Solution: core2.0ubuntu
1. How to obtain the Client IP address (extension class)
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 // extended class 10 /// </summary> 11 public static class Extension12 {13 /// <summary> 14 // /obtain the customer's Ip15 // </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}
Call this method:
var ip = HttpContext.GetClientUserIp();
2. solve the problem that the client IP address cannot be correctly obtained after Asp. Net Core2.0 is released to Ubuntu.
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 solves the problem that the Ubuntu Nginx agent cannot obtain IP address 10 app. useForwardedHeaders (new ForwardedHeadersOptions11 {12 ForwardedHeaders = ForwardedHeaders. XForwardedFor | ForwardedHeaders. XForwardedProto13}); 14 # endregion15}
My site uses Nginx for proxy, and the site points to a local Ip address, and the customer's IP address cannot be obtained correctly. In this case, you need to pass the IP address obtained through Nginx to the site
Nginx Configuration
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 }
Restart Nginx:
sudo service nginx restart;