繁体   English   中英

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

[英]Getting Client IP address in WCF with 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地址吗? 先感谢您

发生这种情况是因为在wsDualHttpBinding情况下, RemoteEndpointMessageProperty.Address属性显示为空。

RemoteEndpointMessageProperty使用HttpApplication.Request.UserHostAddress返回IP。 但是, HttpContextWSDualHttpBinding不可用,从而导致“请求在上下文中不可用”异常。

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

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

终于用@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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM