【发布时间】:2012-09-18 10:23:15
【问题描述】:
我尝试了Request.UserHostAddress;,但 API 控制器在 Request 中没有 UserHostAddress。
【问题讨论】:
-
对不起,我很困惑。检查另一个问题:stackoverflow.com/questions/9565889/…
标签: asp.net-mvc asp.net-mvc-4 asp.net-web-api
我尝试了Request.UserHostAddress;,但 API 控制器在 Request 中没有 UserHostAddress。
【问题讨论】:
标签: asp.net-mvc asp.net-mvc-4 asp.net-web-api
根据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"];
【讨论】:
HTTP_X_FORWARDED_FOR 可能包含多个地址。您应该检查一下。 Example
IP = ((HttpContextBase)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
【讨论】:
我正在使用以下代码,它对我有用....
string ipAddress = System.Web.HttpContext.Current.Request.UserHostAddress;
【讨论】: