使用C# .NET 3.5和WCF,我尝试在客户端应用程序中写出一些WCF配置(客户端连接到的服务器的名称)。
最明显的方法是使用ConfigurationManager
加载配置节并写出我需要的数据。
var serviceModelSection = ConfigurationManager.GetSection("system.serviceModel");
似乎总是返回null。
var serviceModelSection = ConfigurationManager.GetSection("appSettings");
效果很好。
配置部分存在于App.config中,但是出于某种原因,ConfigurationManager
拒绝加载system.ServiceModel
部分。
我希望避免手动加载xxx.exe.config文件和使用XPath,但如果必须这样做,我会这样做。只是看起来有点像黑客。
有什么建议吗?
发布于 2008-08-21 10:35:09
http://mostlytech.blogspot.com/2007/11/programmatically-enumerate-wcf.html
// 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 ...
看起来效果很好。
发布于 2008-08-21 10:51:08
这就是我一直在寻找的东西,感谢@marxidad的指针。
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;
}
发布于 2011-05-13 10:19:36
GetSectionGroup()不支持任何参数(在框架3.5下)。
请改用:
Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ServiceModelSectionGroup group = System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup(config);
https://stackoverflow.com/questions/19589
复制相似问题