我试图在控制器中获取客户端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地址有什么不同的方法吗?
答案 0 :(得分:11)
从Controller
:
方法1:
string userIpAddress = this.Request.ServerVariables["REMOTE_ADDR"];
方法2:
string userIpAddress = this.Request.UserHostAddress;
答案 1 :(得分:4)
尝试:
HttpContext.Request.UserHostAddress
http://msdn.microsoft.com/en-us/library/system.web.httprequest.userhostaddress%28v=vs.110%29.aspx
答案 2 :(得分:1)
以下代码行帮助了我:
string ip = System.Web.HttpContext.Current.Request.UserHostAddress;