![](/img/trans.png)
[英]How to programmatically modify WCF app.config endpoint address setting?
[英]Can I programmatically override client app.config WCF endpoint addresses?
我想覆蓋存儲在app.config中的客戶端WCF終結點地址,以便可以將它們從指向“本地主機”更改為指向生產URL [取決於可以在App內部設置的配置(包含在對象'appConfig'中)在下面顯示的代碼中)-這是一個WinForms項目。]
通過閱讀該領域的其他問題,我到達了以下代碼(從InitEndpoints調用InitEndpoint),這些代碼是我從Form_Load事件調用的。 我在應用程序中嘗試了這些,如果將鼠標懸停在“ ep”變量中的值上,它們似乎會更改端點地址。 但是,如果我在代碼之后再次通過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);
}
}
我這樣做的唯一方法是在每個客戶端的構造實例上替換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 ...
}
我通過在客戶端代理中使用ClientBase <>構造函數來修改客戶端上wcf服務的端點
public class JournalProxy : ClientBase<IJournal>, IJournal
{
public JournalProxy()
: base(binding, endpointAddress)
{
}
public string StoreJournal(JournalInformation journalToStore)
{
return Channel.StoreJournal(journalToStore);
}
}
在我的情況下,我從客戶端代理中的數據庫設置創建綁定和端點,您也許可以使用ClientBase(string endpointConfigurationName,string remoteAddress)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.