gpt4 book ai didi

c# - 如何在 MVC 4 Controller 中获取客户端 IP 地址?

转载 作者:行者123 更新时间:2023-11-30 13:14:54 36 4
gpt4 key购买 nike

我试图在 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;

关于c# - 如何在 MVC 4 Controller 中获取客户端 IP 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22662933/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com