2012-09-26 19 views
14

Request.UserHostAddress;を試しましたが、APIコントローラにリクエスト内にUserHostAddressがありません。ASP.NET MVC APIコントローラでユーザIPを取得する方法

+1

申し訳ありませんが、混乱しました。この他の質問をチェックしてください:http://stackoverflow.com/questions/9565889/get-the-ip-address-of-the-remote-host –

答えて

16
IP = ((HttpContextBase)request.Properties["MS_HttpContext"]).Request.UserHostAddress; 
6

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"]; 
+1

少し余分な研究をしました。あなたがサーバー変数の要求ヘッダー。 context.Request.ServerVariables ["HTTP_X_FORWARDED_FOR"]は、プロキシサーバとロードバランサによって送信されたX-Forward-Forリクエストヘッダを取得しています。 – muglio

11

私は次のコードを使用しています。それは私のために機能します....

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

ホストアドレスを与える –

関連する問題