如何在ASP.NET MVC API控制器中获取用户IP

use*_*362 17 asp.net-mvc asp.net-mvc-4 asp.net-web-api

我试过Request.UserHostAddress;但是API控制器在Request中没有UserHostAddress.

San*_*ndo 19

IP = ((HttpContextBase)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
Run Code Online (Sandbox Code Playgroud)


Md.*_*lam 11

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

string ipAddress =   System.Web.HttpContext.Current.Request.UserHostAddress;
Run Code Online (Sandbox Code Playgroud)


Gar*_*lie 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

if (String.IsNullOrEmpty(IPAddress))
    IPAddress = Request.ServerVariables["REMOTE_ADDR"];
Run Code Online (Sandbox Code Playgroud)

  • 我最后做了一些额外的研究,因为你会在服务器变量中选择一个请求标头感到奇怪.context.Request.ServerVariables ["HTTP_X_FORWARDED_FOR"]正在接收由代理服务器和负载均衡器发送的X-Forward-For请求标头. (2认同)