【问题标题】:What is the difference between the process of consuming WCF in Windows app and in Silverlight?在 Windows 应用和 Silverlight 中使用 WCF 的过程有什么区别?
【发布时间】:2011-03-25 03:39:46
【问题描述】:

我有一个 WCF 函数“string GetDetails(int x,int y)”,它现在部署在 Windows 应用程序中的服务器上。我可以通过写来调用它的函数

ServiceReference1.ServiceClient objService = new ServiceReference1.ServiceClient(); 字符串数据 = objService.GetData(10,23);

但在 Silverlight 中我无法做到这一点。为什么?

【问题讨论】:

    标签: silverlight wcf


    【解决方案1】:

    因为 SL 只允许来自服务客户端的异步调用(但这并不一定意味着您的操作在服务器上是异步的)。

    您必须执行以下操作:

    ServiceReference1.ServiceClient objService = new ServiceReference1.ServiceClient(); 
    objService.GetDataCompleted += OnGetDataCompleted;
    objService.GetData(10,23);
    
    private void OnGetDataCompleted(object sender, GetDataCompletedEventArgs e)
    {
      if (e.Error == null)
      {
        string data = e.Result;
        // Do something with data
      }
    }
    

    【讨论】:

    • 需要注意的是,SL 之所以只允许异步调用,是因为 SL 在 UI 线程上执行,非异步会阻塞 UI 更新。您可以在 SL 中生成线程,但让一切都异步是 UI 应用程序的更好模式,并且强制执行这一点可以避免程序员不得不用复杂的线程管理代码乱扔代码(尽管它真的没有那么复杂)。
    【解决方案2】:

    您可能还想阅读 ClientAccessPolicy.xml。这是一个good link 在这里。简而言之,您的服务必须允许通过 ClientAccessPolicy.xml 文件授予 Silverlight 客户端访问其域的权限来调用自己。这通常通过创建服务(可以在托管服务的同一项目中实现)来完成,以确保 ClientAccessPolicy.xml 文件在正确的位置可用。

    如果您的服务是自托管的,您可以将这样的代码添加到您的服务启动(主):

            // This service is used to retrieve the client access policy to allow for cross-domain service calls.
            ServiceHost ClientAccessPolicyService = null;
            ClientAccessPolicyService = new ServiceHost(typeof(ClientAccessPolicyService));
            ClientAccessPolicyService.Open();
    

    这样的行(来自我们目前正在开发的项目,我确信这些设置将在我们部署时得到改进)被添加到您的服务的 app.config 文件中:

      <service name="ClientAccessPolicyService">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8731/"/>
          </baseAddresses>
        </host>
        <endpoint address=""
                  binding="webHttpBinding"
                  contract="IClientAccessPolicy"
                  behaviorConfiguration="HttpEnableBehavior">
        </endpoint>
      </service>
    
      <endpointBehaviors>
        <behavior name="HttpEnableBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    

    其中 ClientAccessPolicyService 是提供 ClientAccessPolicy.xml 文件的服务,而 IClientAccessPolicy 是 OperationContract。

    希望在此信息和上述链接(及其嵌入式链接)上的信息之间,您能够从 Silverlight 访问您的服务。我可能会遗漏更多内容,但我自己真的才刚刚开始使用 WCF 和 Silverlight,所以我很幸运能够运行某些东西

    祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-15
      • 1970-01-01
      • 2015-12-26
      • 2010-11-21
      • 1970-01-01
      相关资源
      最近更新 更多