2017-07-21 66 views
0

我使用下面的代碼在我的服務獲取客戶端的IP地址在WCF與wsDualHttpBinding

public class HeartBeat : IHeartBeat 
{ 
    public string GetData() 
    { 
     OperationContext context = OperationContext.Current; 
     MessageProperties prop = context.IncomingMessageProperties; 
     RemoteEndpointMessageProperty endpoint = 
      prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; 
     string ip = endpoint.Address; 

     return "IP address is: " + ip; 
    } 
} 

我注意到,如果我的網絡配置是:

<protocolMapping> 
    <add binding="basicHttpBinding" scheme="http" /> 
</protocolMapping> 

我能成功獲得IP地址。但是,如果我使用這樣的雙http綁定:

<protocolMapping> 
    <add binding="wsDualHttpBinding" scheme="http" /> 
</protocolMapping>  

我得到一個空返回。有沒有其他方法可以在wsDualHttpBinding中獲取客戶端的IP地址?預先感謝您

回答

0

終於想出用@Neel

上花花公子
public class HeartBeat : IHeartBeat 
{ 
    public string GetData() 
    { 
     OperationContext context = OperationContext.Current; 
     MessageProperties prop = context.IncomingMessageProperties; 
     RemoteEndpointMessageProperty endpoint = 
      prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; 
     string ip = endpoint.Address; 

     EndpointAddress test = OperationContext.Current.Channel.RemoteAddress; 
     IPHostEntry ipHostEntry = Dns.GetHostEntry(System.ServiceModel.OperationContext.Current.Channel.RemoteAddress.Uri.Host); 

     foreach (IPAddress ip2 in ipHostEntry.AddressList) 
     { 
      if (ip2.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) 
      { 
       //System.Diagnostics.Debug.WriteLine("LocalIPadress: " + ip); 
       return ip2.ToString(); 
      } 
     } 

     return "IP address is: " + System.ServiceModel.OperationContext.Current.Channel.RemoteAddress.Uri.Host; 
    } 
} 
1

發生這種情況是因爲RemoteEndpointMessageProperty.Address屬性在wsDualHttpBinding的情況下顯示爲空。

RemoteEndpointMessageProperty使用HttpApplication.Request.UserHostAddress來返回IP。 但是,HttpContext不適用於WSDualHttpBinding,導致「請求在上下文中不可用」異常。

您可以嘗試訪問雙通道下方的主機屬性。

if (string.IsNullOrEmpty(endpoint.Address)) 
{ 
    string clientIpOrName = System.ServiceModel.OperationContext.Current.Channel.RemoteAddress.Uri.Host; 
} 
+0

現貨..這是工作。不過我正在電腦名稱,而不是IP地址。無論如何解決這個問題? – Redis1001