我想覆蓋存儲在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);
}
}
這可能是你在找什麼... http://stackoverflow.com/questions/5151077/wcf-change-endpoint-address-at-runtime – 2012-04-25 16:12:11