Сведения о вопросе

LiKIY

15:48, 14th August, 2020

Теги

c#   .net   xml   wcf   configurationmanager    

Загрузка раздела конфигурации System.ServiceModel с помощью ConfigurationManager

Просмотров: 526   Ответов: 5

Используя 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, но если мне придется прибегнуть к этому, я сделаю это. Просто кажется, что это немного халтура.

Есть какие-нибудь предложения?



  Сведения об ответе

VERSUION

10:02, 18th August, 2020

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

Похоже, это хорошо работает.


  Сведения об ответе

lourence

00:44, 6th August, 2020

Элемент <system.serviceModel> предназначен для группы разделов конфигурации, а не для раздела. Вам нужно будет использовать System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup() , чтобы получить всю группу.


  Сведения об ответе

darknet

21:21, 1st August, 2020

Это то,что я искал благодаря @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;
    }


  Сведения об ответе

VERSUION

19:53, 20th August, 2020

GetSectionGroup() не поддерживает никакие параметры (в рамках фреймворка 3.5).

Вместо этого используйте:

Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ServiceModelSectionGroup group = System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup(config);


  Сведения об ответе

lourence

00:47, 16th August, 2020

Благодаря другим плакатам это функция, которую я разработал, чтобы получить 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


Ответить на вопрос

Чтобы ответить на вопрос вам нужно войти в систему или зарегистрироваться