Используя C # .NET 3.5 и WCF, я пытаюсь записать некоторые настройки WCF в клиентском приложении (имя сервера, к которому подключается клиент).
Очевидным способом является ConfigurationManager
загрузка раздела конфигурации и запись нужных мне данных.
var serviceModelSection = ConfigurationManager.GetSection("system.serviceModel");
Кажется, всегда возвращать ноль.
var serviceModelSection = ConfigurationManager.GetSection("appSettings");
Работает отлично.
Раздел конфигурации присутствует в App.config, но по какой-то причине ConfigurationManager
отказывается загружать system.ServiceModel
раздел.
Я хочу избежать ручной загрузки файла xxx.exe.config и использования XPath, но если мне придется прибегнуть к этому, я это сделаю. Похоже, что-то вроде хака.
Какие-либо предложения?
<system.serviceModel>
Элемент для раздела конфигурации группы , а не раздел. Вам нужно будет использовать, System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup()
чтобы получить всю группу.
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 ...
Кажется, работает хорошо.
Это то, что я искал, спасибо @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;
}
GetSectionGroup () не поддерживает никаких параметров (в рамках 3.5).
Вместо этого используйте:
Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ServiceModelSectionGroup group = System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup(config);
Благодаря другим авторам эту функцию я разработал для получения URI указанной конечной точки. Он также создает список используемых конечных точек и какой фактический файл конфигурации использовался при отладке:
Private Function GetEndpointAddress(name As String) As String
Debug.Print("--- GetEndpointAddress ---")
Dim address As String = "Unknown"
Dim appConfig As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
Debug.Print("app.config: " & appConfig.FilePath)
Dim serviceModel As ServiceModelSectionGroup = ServiceModelSectionGroup.GetSectionGroup(appConfig)
Dim bindings As BindingsSection = serviceModel.Bindings
Dim endpoints As ChannelEndpointElementCollection = serviceModel.Client.Endpoints
For i As Integer = 0 To endpoints.Count - 1
Dim endpoint As ChannelEndpointElement = endpoints(i)
Debug.Print("Endpoint: " & endpoint.Name & " - " & endpoint.Address.ToString)
If endpoint.Name = name Then
address = endpoint.Address.ToString
End If
Next
Debug.Print("--- GetEndpointAddress ---")
Return address
End Function