我在安装了IIS8.5的web服务器上部署了一个ASP.NET MVC应用程序(使用.NET 4.5)。
我已经创建了一个自定义控制器类,其中我做了一些事情,它继承了System.Web.Mvc.Controller:
public partial class MyCustomController : System.Web.Mvc.Controller
{
// Here my stuff
}然后,我的所有控制器(少数控制器除外)继承自我的自定义控制器,例如:
public partial class OneController : MyCustomController
{
// Here some stuff
}我的目标是:
发布于 2020-11-10 09:17:32
您可以使用HttpRequest.ServerVariables获取ASP.NET MVC中客户端的IP地址。REMOTE_ADDR变量提供客户端的IP地址。
您可以直接对控制器页面使用下面的方法,并从视图或任何需要的地方调用它。
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;
} 获取IP地址的第二种方法是使用ASP.NET的内置功能,这里我们使用page的Request属性,它为请求的页面获取一个HttpRequest类的对象。HttpRequest是一个密封类,它使ASP.NET能够读取客户端浏览器在Web请求期间发送的HTTP值。我们访问UserHostAddress类的HttpRequest属性来获取访问者的IP地址。
private void GetIpAddress(out string userip)
{
userip = Request.UserHostAddress;
if (Request.UserHostAddress != null)
{
Int64 macinfo = new Int64();
string macSrc = macinfo.ToString("X");
if (macSrc == "0")
{
if (userip == "127.0.0.1")
{
Response.Write("visited Localhost!");
}
else
{
lblIPAdd.Text = userip;
}
}
}
} 发布于 2020-11-06 22:49:50
https://stackoverflow.com/questions/64722540
复制相似问题