引用地址:C# .Net Nginx组合获取客户端真实IP-罗分明网络博客
nginx.conf配置文件部分信息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | server { listen 80; server_name www.luofenming.com; location / { proxy_pass http: //localhost:8711; 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_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection keep-alive; proxy_cache_bypass $http_upgrade; } } |
C# 获取IP帮助类代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | using Microsoft.AspNetCore.Http; using System.Linq; namespace lqwvje { public static class GetHostIP { /// <summary> /// 获取客户Ip /// </summary> /// <param name="context"></param> /// <returns></returns> public static string GetClientUserIp( this HttpContext context) { var userHostAddress = context.Request.Headers[ "X-Forwarded-For" ].FirstOrDefault(); if ( string .IsNullOrEmpty(userHostAddress)) { //这个是直接IP,如果经过反向代理IP会变成代理机的,如果代理机就是本机就会变成127.0.0.1 userHostAddress = context.Connection.RemoteIpAddress.ToString(); } //最后判断获取是否成功,并检查IP地址的格式 if (! string .IsNullOrEmpty(userHostAddress) && IsIP(userHostAddress)) { return userHostAddress; } return "127.0.0.1" ; } /// <summary> /// 检查IP地址格式 /// </summary> /// <param name="ip"></param> /// <returns></returns> public static bool IsIP( string ip) { return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$" ); } } } |
获取IP调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | //Startup.cs 文件注册服务务 public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc( "v1" , new OpenApiInfo { Title = "lqwvje" , Version = "v1" }); }); //注册下面服务 services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>(); } //下面是接口返回IP的方法 [Route( "api/[controller]" )] [ApiController] public class ValuesController : ControllerBase { [HttpGet( "GetIP" )] public string GetIP() { HttpContextAccessor context = new HttpContextAccessor(); return GetHostIP.GetClientUserIp(context.HttpContext); } } |