我的业务层对于WebApi和WebApplication很常见。需要跟踪每个操作的客户端IP地址。在网络上搜索并尝试了此操作,但是在开发中尝试了此操作,但我认为这是针对Server的。我正在获取服务器的IP地址:
var host = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
string ipAddress = host.AddressList[1].ToString();
答案 0 :(得分:1)
您可以尝试以下扩展方法:
public static class HttpContextExtensions
{
public static string GetIpAddress(this HttpContext httpContext)
{
try
{
return httpContext.Connection.RemoteIpAddress.ToString();
}
catch
{
return string.Empty;
}
}
}
旧版.Net版本示例:
/// <summary>
/// Gets the IP address for the current request, returns 0.0.0.0 if HttpsContext does not exist.
/// </summary>
/// <returns></returns>
public static string GetIpAddress()
{
var context = HttpContext.Current;
var ipAddress = String.Empty;
if (context != null)
{
ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (String.IsNullOrWhiteSpace(ipAddress))
{
ipAddress = context.Request.ServerVariables["REMOTE_ADDR"];
}
else
{
var ipAddresses = ipAddress.Split(new [] {','}, StringSplitOptions.RemoveEmptyEntries);
if (ipAddresses.Length > 0)
{
ipAddress = ipAddresses[0];
}
}
ipAddress = String.IsNullOrWhiteSpace(ipAddress) ? context.Request.UserHostName : ipAddress;
}
return String.IsNullOrWhiteSpace(ipAddress) ? "0.0.0.0" : ipAddress;
}