使用wsDualHttpBinding在WCF中获取客户端IP地址

时间:2017-07-21 07:27:36

标签: c# asp.net .net wcf

我在我的服务中使用以下代码

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地址吗?提前谢谢

2 个答案:

答案 0 :(得分:1)

这是因为RemoteEndpointMessageProperty.Address属性wsDualHttpBinding属性为RemoteEndpointMessageProperty

HttpApplication.Request.UserHostAddress使用HttpContext返回IP。 但WSDualHttpBinding无法使用if (string.IsNullOrEmpty(endpoint.Address)) { string clientIpOrName = System.ServiceModel.OperationContext.Current.Channel.RemoteAddress.Uri.Host; } ,导致&#34;请求在上下文中不可用&#34;异常。

您可以尝试访问以下主机属性以获得双通道。

{{1}}

答案 1 :(得分: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;
    }
}