下面的代码在本地运行正常,但它只能获得服务器的IP (如果我是正确的)。
try
{
string externalIP;
externalIP = (new WebClient()).DownloadString("http://checkip.dyndns.org/");
externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
.Matches(externalIP)[0].ToString();
model.IpCreacion = externalIP;
}
catch { }我现在不能测试这个,因为我办公室的两个家伙今天不在这里,他们可以把它作为在服务器上测试的公共URL。代码在项目的控制器中,所以每次客户端执行应用程序时,它都运行在服务器上,而不是真正得到IP地址的客户端。
如何使客户端获得他的IP地址,而不是服务器,执行我刚才显示的代码?
如果我成功地将此功能放到视图中,它是否会像我所打算的那样工作呢?
更新:我尝试了其他作为答案发布的方法,如
string ip = System.Web.HttpContext.Current.Request.UserHostAddress;和
model.IpCreacion = null;
model.IpCreacion = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(model.IpCreacion))
{
model.IpCreacion = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}但现在我只得到::1作为一个结果。以前没发生过,因为我得到了正确的IP地址。
发布于 2020-03-09 14:02:05
这只会获得服务器的IP,因为您将请求从Web发送到checkip.dyndns.org。
要获得客户端IP,您需要使用JavaScript并执行相同的操作。
$.get('http://checkip.dyndns.org/', function(data) {
console.log(data); // client IP here.
})更新:
如果您需要ASP.NET核心中的客户端IP地址,可以插入此服务
private IHttpContextAccessor _accessor;并把它当作
_accessor.HttpContext.Connection.RemoteIpAddress.ToString()或在ASP.NET框架中
Public string GetIp()
{
string ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
{
ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
return ip;
} 发布于 2020-03-09 14:05:52
如果您想获取客户端ip地址,请访问堆栈溢出How can I get the client's IP address in ASP.NET MVC?中的下面的帖子。
发布于 2020-03-09 15:06:47
Public string GetIp()
{
string ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
{
ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
return ip;
} https://stackoverflow.com/questions/60602107
复制相似问题