WCF配置增强
背景
在app.config
或web.config
中,可以在以下位置定义配置条目:
<appSettings>...</appSettings>
像这样:
<add key="MyKey" value="%SomeEnvironmentVariable%"/>
此后,为了检索与MyKey
相关联的值,可以使用以下两行代码:
string raw = ConfigurationManager.AppSettings[“MyKey”];
string cooked = (raw == null) ? null : Environment.ExpandEnvironmentVariables(raw);
问题:
是否有办法对WCF服务配置执行相同操作,例如:
<system.serviceModel>
. . .
<services>
<service name="..." ...>
. . .
<endpoint
address="%MyEndPointAddress%" ... />
. . .
</service>
</services>
</system.serviceModel>
任何知识都将受到高度赞赏。
- 阿维
答案 0 :(得分:1)
要更改端点地址,您需要知道EndPointName和ContractName。此值可在WCF配置中的配置文件中找到。然后您可以使用以下代码:
void SetNewEndpointAddress(string endpointName, string contractName, string newValue)
{
bool settingsFound = false;
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ClientSection section = config.GetSection("system.serviceModel/client") as ClientSection;
foreach (ChannelEndpointElement ep in section.Endpoints)
{
if (ep.Name == endpointName && ep.Contract == contractName)
{
settingsFound = true;
ep.Address = new Uri(newValue);
config.Save(ConfigurationSaveMode.Full);
}
}
if (!settingsFound)
{
throw new Exception(string.Format("Settings for Endpoint '{0}' and Contract '{1}' was not found!", endpointName, contractName));
}
}
快乐的编码!