首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用ConfigurationManager加载System.ServiceModel配置节

使用ConfigurationManager加载System.ServiceModel配置节
EN

Stack Overflow用户
提问于 2008-08-21 10:27:59
回答 4查看 59.3K关注 0票数 64

使用C# .NET 3.5和WCF,我尝试在客户端应用程序中写出一些WCF配置(客户端连接到的服务器的名称)。

最明显的方法是使用ConfigurationManager加载配置节并写出我需要的数据。

代码语言:javascript
复制
var serviceModelSection = ConfigurationManager.GetSection("system.serviceModel");

似乎总是返回null。

代码语言:javascript
复制
var serviceModelSection = ConfigurationManager.GetSection("appSettings");

效果很好。

配置部分存在于App.config中,但是出于某种原因,ConfigurationManager拒绝加载system.ServiceModel部分。

我希望避免手动加载xxx.exe.config文件和使用XPath,但如果必须这样做,我会这样做。只是看起来有点像黑客。

有什么建议吗?

EN

回答 4

Stack Overflow用户

发布于 2008-08-21 10:35:09

http://mostlytech.blogspot.com/2007/11/programmatically-enumerate-wcf.html

代码语言:javascript
复制
// Automagically find all client endpoints defined in app.config
ClientSection clientSection = 
    ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection;

ChannelEndpointElementCollection endpointCollection =
    clientSection.ElementInformation.Properties[string.Empty].Value as     ChannelEndpointElementCollection;
List<string> endpointNames = new List<string>();
foreach (ChannelEndpointElement endpointElement in endpointCollection)
{
    endpointNames.Add(endpointElement.Name);
}
// use endpointNames somehow ...

看起来效果很好。

票数 64
EN

Stack Overflow用户

发布于 2008-08-21 10:51:08

这就是我一直在寻找的东西,感谢@marxidad的指针。

代码语言:javascript
复制
    public static string GetServerName()
    {
        string serverName = "Unknown";

        Configuration appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        ServiceModelSectionGroup serviceModel = ServiceModelSectionGroup.GetSectionGroup(appConfig);
        BindingsSection bindings = serviceModel.Bindings;

        ChannelEndpointElementCollection endpoints = serviceModel.Client.Endpoints;

        for(int i=0; i<endpoints.Count; i++)
        {
            ChannelEndpointElement endpointElement = endpoints[i];
            if (endpointElement.Contract == "MyContractName")
            {
                serverName = endpointElement.Address.Host;
            }
        }

        return serverName;
    }
票数 16
EN

Stack Overflow用户

发布于 2011-05-13 10:19:36

GetSectionGroup()不支持任何参数(在框架3.5下)。

请改用:

代码语言:javascript
复制
Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ServiceModelSectionGroup group = System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup(config);
票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19589

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档