使用WCF服务的Silverlight客户端会抛出System.ServiceModel.CommunicationException

时间:2014-07-02 06:09:22

标签: c# wcf silverlight nettcpbinding clientaccesspolicy.xml

请耐心等待我,因为我是WCF服务/ Windows服务的菜鸟。我已经创建了一个托管在Windows服务中的WCF服务。我想在Silverlight浏览器中的应用程序中使用WCF服务。下面是Silverlight中用于访问WCF服务的代码片段:


            var messageEncoding = new BinaryMessageEncodingBindingElement();
            var tcpTransport = new TcpTransportBindingElement();
            var binding = new CustomBinding(messageEncoding, tcpTransport);

            // Create a channel factory for the service endpoint configured with the custom binding.
            var cf = new ChannelFactory<ICalcService>(binding, new EndpointAddress("net.tcp://192.168.2.104:4508"));

            // Open the channel.
            ICalcService channel = cf.CreateChannel();

            // Invoke the method asynchronously.
            channel.BeginAdd(9, 5, AddCallback, channel);

    private void AddCallback(IAsyncResult asyncResult)
    {
        try
        {
            double endAdd = ((ICalcService) asyncResult.AsyncState).EndAdd(asyncResult);
        }
        catch (Exception exception)
        {
            throw exception;
        }
    }

我可以在其他本地非Silverlight应用程序中使用WCF服务而没有任何异常。但是在Silverlight中,它会抛出异常 System.ServiceModel.CommunicationException ,并显示以下消息:

Could not connect to net.tcp://192.168.2.104:4508/. The connection attempt lasted for a time span of 00:00:00.1010058. TCP error code 10013: An attempt was made to access a socket in a way forbidden by its access permissions.. This could be due to attempting to access a service in a cross-domain way while the service is not configured for cross-domain access. You may need to contact the owner of the service to expose a sockets cross-domain policy over HTTP and host the service in the allowed sockets port range 4502-4534.

System.Net.Sockets.SocketException 类型的innerException表示

An attempt was made to access a socket in a way forbidden by its access permissions.

谷歌搜索建议我解决方案,如禁用防火墙,在ClientAccessPolicy.xml中添加以下标签:

  <grant-to>
    <socket-resource port="4502-4534" protocol="tcp" />
  </grant-to>

不幸的是,这些解决方案都没有帮助我。我想这个问题与ClientAccessPolicy.xml有关。我怀疑我错过了将ClientAccessPolicy.xml放在正确的位置。我把它保存在WCF服务的根目录下。这对netTcpBinding有用吗?如果ClientAccessPolicy.xml不是罪魁祸首,那么这个异常背后可能是什么原因?

1 个答案:

答案 0 :(得分:0)

摆脱异常.. !!我在服务实现之前添加了以下属性:

    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

Aslo我在指定绑定时删除了安全模式:

var netTcpBinding = new NetTcpBinding(SecurityMode.None);