从 ASP.NET MVC 中的请求获取客户端 IP 地址

问题描述 投票:0回答:2

我在安装了 IIS 8.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
}

我的目标:

  1. 现在,我需要获取当前正在创建的客户端IP地址 向我的 ASP.NET MVC 应用程序发出请求。所以我想实施 我的自定义控制器 MyCustomController 中的一个方法 返回该客户端 IP。目前这可能吗?如果是的话怎么办?
  2. 另外,我如何知道传入的请求是否来自本地IP地址(localhost)127.0.0.1,如果是,则丢弃该请求,我的意思是,什么都不做?
c# asp.net-mvc asp.net-4.5
2个回答
3
投票

您可以使用 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 值。我们访问 HttpRequest 类的 UserHostAddress 属性来获取访问者的 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;  
         }     
     }  
  }  
}  

2
投票

试试这个属性:

System.Web.HttpContext.Current.Request.UserHostAddress

您可以使用自己实现的ActionFilterAttribute来过滤请求

© www.soinside.com 2019 - 2024. All rights reserved.