2012-04-25 202 views
1

我想覆蓋存儲在app.config中的客戶端WCF端點地址,以便我可以將它們從指向「localhost」的位置更改爲指向生產URL [取決於可以從App中設置的配置(包含在「對象」下面顯示的代碼中的'appConfig') - 這是一個WinForms項目。]我可以以編程方式覆蓋客戶端app.config WCF端點地址嗎?

通過閱讀此區域中的其他問題,我已經達到了從Form_Load事件調用的下列代碼段(調用InitEndpoint的InitAllEndpoints)。我在我的應用程序中嘗試了這些,如果我將鼠標懸停在「ep」變量的值上,它們似乎會更改EndPoint地址。然而,如果我通過serviceModelSectionGroup.Client.Endpoints再次循環我的代碼後,我發現它們事實上沒有改變。 (我現在讀的EndPoint地址是不可變的 - 所以我的代碼看起來錯了,因爲我希望用新的EndPoint地址對象覆蓋地址 - 而不是Uri?)

我該如何以編程方式覆蓋客戶端app.config WCF端點地址?

private void InitAllEndpoints() 
{ 
    ServiceModelSectionGroup serviceModelSectionGroup = 
       ServiceModelSectionGroup.GetSectionGroup(
       ConfigurationManager.OpenExeConfiguration(
       ConfigurationUserLevel.None)); 
    if (serviceModelSectionGroup != null) 
    { 

     foreach (ChannelEndpointElement ep in serviceModelSectionGroup.Client.Endpoints) 
     { 
      InitEndpoint(ep, 

       appConfig.ExternalComms_scheme, 
       appConfig.ExternalComms_host, 
       appConfig.ExternalComms_port); 
     } 
    } 
} 


private void InitEndpoint(ChannelEndpointElement endPoint, string scheme, String host, String port) 
{ 
    string portPartOfUri = String.Empty; 
    if (!String.IsNullOrWhiteSpace(port)) 
    { 
     portPartOfUri = ":" + port; 
    } 

    string wcfBaseUri = string.Format("{0}://{1}{2}", scheme, host, portPartOfUri); 

    endPoint.Address = new Uri(wcfBaseUri + endPoint.Address.LocalPath); 
} 

注意:我的代理服務器位於單獨的項目/ DLL中。

例如

public class JournalProxy : ClientBase<IJournal>, IJournal 
{ 
    public string StoreJournal(JournalInformation journalToStore) 
    { 
     return Channel.StoreJournal(journalToStore); 
    } 


} 
+1

這可能是你在找什麼... http://stackoverflow.com/questions/5151077/wcf-change-endpoint-address-at-runtime – 2012-04-25 16:12:11

回答

5

我完成此操作的唯一方法是替換客戶端的每個構建實例上的EndpointAddress

using (var client = new JournalProxy()) 
{ 
    var serverUri = new Uri("http://wherever/"); 
    client.Endpoint.Address = new EndpointAddress(serverUri, 
                client.Endpoint.Address.Identity, 
                client.Endpoint.Address.Headers); 

    // ... use client as usual ... 
} 
1

我完成由utlizing的ClientBase <>構造函數中的客戶端代理修改客戶端上的WCF服務的端點

MDSN - ClientBase

public class JournalProxy : ClientBase<IJournal>, IJournal 
{  

    public JournalProxy() 
     : base(binding, endpointAddress) 
    { 
    } 

    public string StoreJournal(JournalInformation journalToStore)  
    {   
     return Channel.StoreJournal(journalToStore);  
    } 
} 

在我來說,我創建綁定和從客戶端代理中的數據庫設置的端點,您可能能夠使用ClientBase(字符串endpointConfigurationName,字符串remoteAddress)代替

相關問題