如何从单独的配置中读取WCF ClientSection

时间:2014-01-21 00:15:22

标签: c# wcf

我的客户端部分位于单独的配置文件中,如下所示。

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <client>
        <endpoint name="ep1 />
        <endpoint name="ep2 />
        <endpoint name="ep3 />
    </client>
</configuration>

我试过两个版本的配置文件(第二个是上面的那个)。原始版本没有xmlconfiguration标记。当这些标签不存在时(我认为这是正确的),我试图用OpenMappedExeConfiguration方法打开文件时出错。

System.Configuration.ConfigurationErrorsException : 
Configuration file Web_ServiceModel_Client.config does not have root 
<configuration> tag ([PATH]\Web_ServiceModel_Client.config line 8)

我想阅读客户端部分,但是,它总是为空。我的尝试

string configPath = Path.Combine(Config.AppPath, "Web_ServiceModel_Client.config");
ExeConfigurationFileMap map = new ExeConfigurationFileMap { ExeConfigFilename = configPath };
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

ClientSection cs1 = config.Sections["client"] as ClientSection;
ClientSection cs2 = config.GetSection("client") as ClientSection;

cs1和cs2都为空。

我如何阅读客户端部分,以便循环使用端点?

ChannelEndpointElement selectedEndpoint = null;
foreach (ChannelEndpointElement endpoint in cs1.Endpoints)
{
    if (endpoint.Name == "MyServiceName")
    {
        selectedEndpoint = endpoint;
        break;
    }
}

其他
config.Sections("client") is DefaultSection。因此,当我将其转换为ClientSection时,它为空。为什么它是DefaultSection,为什么我不能将它投射到ClientSection

当我尝试以下

ServiceModelSectionGroup group = ServiceModelSectionGroup.GetSectionGroup(config);
var client = group.Client;

//client.EndPoints.Count == 0 !!!

1 个答案:

答案 0 :(得分:2)

我假设您有一个主配置文件,如下所示:

<configuration>
  ...
  <system.serviceModel>
    ...
    <client configSource="Web_ServiceModel_Client.config" />      
    ...
  </system.serviceModel>
</configuration>

而且您正在询问如何从外部配置文件中读取值( Web_ServiceModel_Client.config )。您的代码存在两个问题:

  1. 您正在打开错误的配置文件。您应该打开主配置文件(带有<configuration/>标记的文件),而不是打开外部配置文件:

    string configPath = Path.Combine(Config.AppPath, "Main_Configuration_File.config");
    ExeConfigurationFileMap map = new ExeConfigurationFileMap { ExeConfigFilename = configPath };
    Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
    
  2. 你使用错误的部分名称。我假设ClientSectionSystem.ServiceModel.Configuration.ClientSection,因此根据其配置路径,您应该将system.serviceModel/client作为sectionName传递:

    ClientSection cs2 = config.GetSection("system.serviceModel/client") as ClientSection;