2017-05-18 12 views
2

我想使用代碼而不是app.config來綁定我的WCF客戶端,因爲我需要更改不同部署的主機IP地址。WCF動態綁定 - 如何指定結束點?

這是我的app.config:

<?xml version="1.0" encoding="utf-8"?> 
<configuration> 
    <startup> 
     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/> 
    </startup> 
    <system.serviceModel> 
     <bindings> 
      <wsHttpBinding> 
       <binding name="WSHttpBinding_ICX" maxReceivedMessageSize="1073741824" > 
        <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /> 
       </binding> 
      </wsHttpBinding> 
     </bindings> 
     <client> 
      <endpoint address="http://127.0.0.1/CX/CX.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ICX" contract="CXService.ICX" name="WSHttpBinding_ICX"> 
       <identity> 
        <servicePrincipalName value="host/SilverStar" /> 
       </identity> 
      </endpoint> 
     </client> 
    </system.serviceModel> 
</configuration> 

,這是我的代碼:

public static void StartUp() 
{ 
    XmlDictionaryReaderQuotas quota = new XmlDictionaryReaderQuotas(); 
    quota.MaxArrayLength = 2147483647; 
    quota.MaxBytesPerRead = 2147483647; 
    quota.MaxDepth = 2147483647; 
    quota.MaxNameTableCharCount = 2147483647; 
    quota.MaxStringContentLength = 2147483647; 
    EndpointAddress addr = new EndpointAddress(new Uri("http://127.0.0.1/CX/CX.svc")); 

    WSHttpBinding binding1 = new WSHttpBinding(); 
    binding1.Name = "WSHttpBinding_ICX"; 
    binding1.MaxReceivedMessageSize = 1073741824; 
    binding1.ReaderQuotas = quota; 

    // Globals.CXClient is the client object 
    Globals.CXClient = new CXService.CXClient(binding1, addr); 

    // This line does not compile! Endpoint is read-only!! 
    Globals.CXClient.Endpoint = new ServiceEndpoint(new ContractDescription("CXService.ICX"), (Binding)binding1, addr); 
} 

代碼不編譯爲.EndPoint的最後一行是隻讀屬性。

請幫忙。

+0

看看[this](https://msdn.microsoft.com/en-us/library/ff647110.aspx)網站。 –

回答

1

試試這個:

Globals.CXClient.Endpoint.Address = new System.ServiceModel.EndpointAddress("your url here"); 
0

這是我做到了。

Globals.CXClient.Endpoint.Contract = new ContractDescription("CXService.ICX"); 
Globals.CXClient.Endpoint.Binding = binding1; 
Globals.CXClient.Endpoint.Address = addr; 

但是,我遇到了另一個問題。我試圖更換部分:通過使用下面的代碼

<identity> 
    <servicePrincipalName value="host/SilverStar" /> 
</identity> 

addr.Identity = new SpnEndpointIdentity("host/SilverStar"); 

這一次再次編譯失敗,因爲addr.Identity是隻讀的。

我也試過這樣:

EndpointAddress addr = new EndpointAddress(new Uri("http://127.0.0.1/CX/CX.svc"), new SpnEndpointIdentity("host/SilverStar"), ???); 

但最後一個參數是一個AddressHeaderCollection,我不知道應該放在那裏。

請再次幫忙。謝謝。