【问题标题】:WCF Configuration enhancementWCF 配置增强
【发布时间】:2014-11-14 08:48:09
【问题描述】:

WCF 配置增强

背景:

app.configweb.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>

任何知识都将受到高度赞赏。

--Avi

【问题讨论】:

    标签: c# wcf configuration


    【解决方案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));
            }
        }
    

    编码愉快!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-18
      • 1970-01-01
      • 2012-05-14
      • 2011-07-19
      • 2020-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多