Dot-Net

wcf 服務綁定中的相對 url

  • October 25, 2013

我有一個silverlight 控制項,它引用了啟用silverlight 的wcf 服務。

當我在 silverlight 控制項中添加對服務的引用時,它會將以下內容添加到我的 clientconfig 文件中:

<configuration>
   <system.serviceModel>
       <bindings>
           <basicHttpBinding>
               <binding name="BasicHttpBinding_DataAccess" maxBufferSize="2147483647"
                   maxReceivedMessageSize="2147483647">
                   <security mode="None" />
               </binding>
           </basicHttpBinding>
       </bindings>
       <client>
           <endpoint address="http://localhost:3097/MyApp/DataAccess.svc"
               binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_DataAccess"
               contract="svcMyService.DataAccess" name="BasicHttpBinding_DataAccess" />
       </client>
   </system.serviceModel>
</configuration>

如何在端點地址中指定相對 url 而不是絕對 url?無論我將 Web 應用程序部署到何處,我都希望它能夠工作,而無需編輯 clientconfig 文件,因為 silverlight 組件和 Web 應用程序將始終一起部署。我以為我可以只指定“DataAccess.svc”,但它似乎不喜歡那樣。

您不能在客戶端端點配置中使用相對 URI。您可以做的只是向您的代理類添加另一個建構子,該建構子將採用某種 URL 參數,您可能可以從另一個配置值或使用 Dns 類方法之一獲取這些參數。

我的解決方案:

我沒有使用 devault 建構子(它使用 ServiceReferences.ClientConfig 文件)來實例化我的代理類,而是使用以下內容:

svcMyService.DataAccessClient svcProxy_m;

System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding();

/*
Create an end point, build a an absolute uri reference by specifing the host address and a relative referece to the service page.
Application.Current.Host.Source will be something like Http://server/app/ClientBin/SilverlightApp.xap"<br/><br/>
Specifying Uri(Application.Current.Host.Source, "../DataAccess.svc")); will return "Http://server/app/DataAccess.svc"
*/

System.ServiceModel.EndpointAddress address = new System.ServiceModel.EndpointAddress(new Uri(Application.Current.Host.Source, "../DataAccess.svc"));

svcProxy_m = new svcMyService.DataAccessClient(binding, address);

引用自:https://stackoverflow.com/questions/373219