简体   繁体   English

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

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

I tried to get client IP adress in controller.我试图在控制器中获取客户端 IP 地址。 It is working but sometimes I get this error:它正在工作,但有时我会收到此错误:

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);

Is there any different method for getting client IP address?获取客户端IP地址有什么不同的方法吗?

Either of these should work, from inside your Controller :这些中的任何一个都应该从您的Controller内部工作:

method 1:方法一:

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

method 2:方法二:

string userIpAddress = this.Request.UserHostAddress;

以下代码行帮助了我:

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

System.Web.HttpContext.Current.Request.UserHostAddress this gives user host address and it's not real request IP. System.Web.HttpContext.Current.Request.UserHostAddress 这给出了用户主机地址,它不是真正的请求 IP。

Request.ServerVariables["REMOTE_ADDR"] also returns the same. Request.ServerVariables["REMOTE_ADDR"] 也返回相同的值。

Because if the request has been passed on by one, or more, proxy servers then the IP address returned by HttpRequest.UserHostAddress property will be the IP address of the last proxy server that relayed the request.因为如果请求已由一个或多个代理服务器传递,则 HttpRequest.UserHostAddress 属性返回的 IP 地址将是最后一个中继请求的代理服务器的 IP 地址。

You can use this string manipulation to get the correct Ip of the request您可以使用此字符串操作来获取请求的正确 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