.net Core
获得服务器本地的IP地址:注意,不是获得客户端IP地址
string IP = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.FirstOrDefault(address => address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)?.ToString();
获得客户端IP地址:
/// <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; } }
string IP = HttpContext.GetClientUserIp();
解决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 }
.NetFramework
public static class HttpRequestMessageExtensions { private const string HttpContext = "MS_HttpContext"; private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty"; private const string OwinContext = "MS_OwinContext"; public static string GetClientIpAddress(this HttpRequestMessage request) { // Web-hosting. Needs reference to System.Web.dll if (request.Properties.ContainsKey(HttpContext)) { dynamic ctx = request.Properties[HttpContext]; if (ctx != null) { return "" + ctx.Request.UserHostAddress; } } // Self-hosting. Needs reference to System.ServiceModel.dll. if (request.Properties.ContainsKey(RemoteEndpointMessage)) { dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage]; if (remoteEndpoint != null) { return "" + remoteEndpoint.Address; } } // Self-hosting using Owin. Needs reference to Microsoft.Owin.dll. if (request.Properties.ContainsKey(OwinContext)) { dynamic owinContext = request.Properties[OwinContext]; if (owinContext != null) { return "" + owinContext.Request.RemoteIpAddress; } } return null; } }