繁体   English   中英

如何在 MVC 4 控制器中获取客户端 IP 地址?

[英]How to get client IP address in MVC 4 controller?

我试图在控制器中获取客户端 IP 地址。 它正在工作,但有时我会收到此错误:

The underlying connection was closed: An unexpected error occurred on a receive


        String IP = "";

        using (WebResponse response = request.GetResponse())
        {
            using (StreamReader stream = new StreamReader(response.GetResponseStream()))
            {
                IP = stream.ReadToEnd();
            }
        }

        int first = IP.IndexOf("Address: ") + 9;
        int last = IP.LastIndexOf("</body>");
        IP = IP.Substring(first, last - first);

获取客户端IP地址有什么不同的方法吗?

这些中的任何一个都应该从您的Controller内部工作:

方法一:

string userIpAddress = this.Request.ServerVariables["REMOTE_ADDR"];

方法二:

string userIpAddress = this.Request.UserHostAddress;

以下代码行帮助了我:

string ip = System.Web.HttpContext.Current.Request.UserHostAddress;

System.Web.HttpContext.Current.Request.UserHostAddress 这给出了用户主机地址,它不是真正的请求 IP。

Request.ServerVariables["REMOTE_ADDR"] 也返回相同的值。

因为如果请求已由一个或多个代理服务器传递,则 HttpRequest.UserHostAddress 属性返回的 IP 地址将是最后一个中继请求的代理服务器的 IP 地址。

您可以使用此字符串操作来获取请求的正确 IP

string ipAddressInfo = request.ServerVariables["HTTP_X_FORWARDED_FOR"]; 
   
if (ipAddressInfo.Split(',') > 0){
  `string clientIpAddress = ipAddressInfo.Split(',')[0];`  

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM