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

use*_*343 3 c# asp.net-mvc-4

我试图在控制器中获取客户端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);
Run Code Online (Sandbox Code Playgroud)

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

Vas*_*ski 11

这些中的任何一个都应该起作用,从你的内部Controller:

方法1:

string userIpAddress = this.Request.ServerVariables["REMOTE_ADDR"];
Run Code Online (Sandbox Code Playgroud)

方法2:

string userIpAddress = this.Request.UserHostAddress;
Run Code Online (Sandbox Code Playgroud)

  • 如果您在localhost上进行测试,您将收到looback地址.如果您收到的请求不是来自本地计算机,它应该按预期工作. (2认同)