asp.net HttpContext.Current.Request.ServerVariables 不工作

标签 asp.net

我正在尝试使用 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/

相关文章:

asp.net - 将变量从自定义过滤器传递到 Controller 操作方法

c# - 在 ASP.NET 2 中使用事件目录组的登录表单

c# - 您将/如何保护您的用户详细信息

asp.net - HttpResponseMessage 不返回 ByteArrayContent - ASP.NET Core

c# - ASP.NET ajax c# 总是返回未定义

asp.net - 在asp.net core中将文件路径转换为URL

javascript - 如何向 asp c# webMethod 发送参数?使用 Ajax Jquery

c# - 使用 jQuery 在 ASP.NET 中进行 AJAX 回调

asp.net - Entity Framework - "New transaction is not allowed because there are other threads running in the session"

c# - 访问转发器控件中的文本框