asp.net HttpContext.Current.Request.ServerVariables不能正常工作

时间:2013-07-15 13:22:38

标签: asp.net

我正在尝试使用asp.net(mvc4)应用获取客户端的公共IP地址。我用的时候 HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]如果给我一个空字符串,当我使用HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]时,它会发送一个字符串,如“:: 1”(不带双引号)。 它与IIS快递有关吗???如何使用asp.net获取客户端IP?

感谢。

1 个答案:

答案 0 :(得分:4)

以下是我用来获取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服务的,因为此代码来自我从WCF和Web项目共享的日志代码,因此您可能只需要第二部分。如果您在开发过程中遇到本地主机,则不会获得IP - 您会注意到“:: 1”。但如果部署在服务器上,您将获得它。