17

我已经尝试过,Request.UserHostAddress;但是 API 控制器在请求中没有 UserHostAddress。

4

3 回答 3

19
IP = ((HttpContextBase)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
于 2012-09-27T11:37:59.920 回答
10

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

string ipAddress =   System.Web.HttpContext.Current.Request.UserHostAddress;
于 2013-10-20T04:38:41.660 回答
8

据此更完整的方法是:

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"];
于 2013-05-27T14:53:42.887 回答