【问题标题】:How to Get User IP in ASP.NET MVC API Controller如何在 ASP.NET MVC API 控制器中获取用户 IP
【发布时间】:2012-09-18 10:23:15
【问题描述】:

我尝试了Request.UserHostAddress;,但 API 控制器在 Request 中没有 UserHostAddress。

【问题讨论】:

标签: asp.net-mvc asp.net-mvc-4 asp.net-web-api


【解决方案1】:

根据this,更完整的方法是:

private string GetClientIp(HttpRequestMessage request)
{
    if (request.Properties.ContainsKey("MS_HttpContext"))
    {
        return ((HttpContext)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
    }
    else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
    {
        RemoteEndpointMessageProperty prop;
        prop = (RemoteEndpointMessageProperty)this.Request.Properties[RemoteEndpointMessageProperty.Name];
        return prop.Address;
    }
    else
    {
        return null;
    }
}

过去,在 MVC 3 项目(不是 API)中,我们曾经使用以下内容:

string IPAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

if (String.IsNullOrEmpty(IPAddress))
    IPAddress = Request.ServerVariables["REMOTE_ADDR"];

【讨论】:

  • 我最终做了一些额外的研究,因为在服务器变量中获取请求标头感觉很奇怪。 context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] 正在获取代理服务器和负载均衡器发送的 X-Forward-For 请求标头。
  • HTTP_X_FORWARDED_FOR 可能包含多个地址。您应该检查一下。 Example
【解决方案2】:
IP = ((HttpContextBase)request.Properties["MS_HttpContext"]).Request.UserHostAddress;

【讨论】:

  • 这不是错字“请求”->“请求”吗??
【解决方案3】:

我正在使用以下代码,它对我有用....

string ipAddress =   System.Web.HttpContext.Current.Request.UserHostAddress;

【讨论】:

  • 它给出了主机地址
猜你喜欢
  • 2014-05-04
  • 1970-01-01
  • 1970-01-01
  • 2012-02-20
  • 1970-01-01
  • 2021-05-02
  • 1970-01-01
  • 2011-02-04
  • 2018-06-18
相关资源
最近更新 更多