我正在尝试使用 asp.net (mvc4) 应用程序获取客户端的公共(public) IP 地址。当我使用
HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
如果给我一个空字符串,当我使用 HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]
它发送这样的字符串“::1”(不带双引号)。
它与IIS Express有关吗???我如何使用 asp.net 获取客户端 IP??
谢谢。
最佳答案
这是我用来获取IP地址的方法:
private static string GetIPAddress()
{
try
{
if (System.ServiceModel.OperationContext.Current != null)
{
var endpoint = OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
return endpoint.Address;
}
if (System.Web.HttpContext.Current != null)
{
// Check proxied IP address
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
return HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] + " via " +
HttpContext.Current.Request.UserHostAddress;
else
return HttpContext.Current.Request.UserHostAddress;
}
}
catch { }
return "Unknown";
}
请注意,第一部分是针对 WCF 服务的,因为此代码来 self 的日志记录代码,它是从 WCF 和 Web 项目共享的,因此您可能只需要第二部分。如果您在开发过程中访问本地主机,您将不会获得 IP——正如您注意到的那样,您将获得“::1”。但如果部署在服务器上,您就会得到它。
关于asp.net HttpContext.Current.Request.ServerVariables 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17655292/