2011-05-23 12 views
11

Cómo puedo código I aC# muestra para leer mis configuraciones de seguridad del cliente:¿Cómo puedo descubrir los puntos finales actuales de mi aplicación C# mediante programación?

<client> 
    <endpoint address="http://mycoolserver/FinancialService.svc" 
     binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IFinancialService" 
     contract="IFinancialService" name="WSHttpBinding_IFinancialService"> 
     <identity> 
     <dns value="localhost" /> 
     </identity> 
    </endpoint> 
    <endpoint address="http://mycoolserver/HumanResourcesService.svc" 
     binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IHumanResourceService" 
     contract="IHumanResourceService" name="WSHttpBinding_IHumanResourceService"> 
     <identity> 
     <dns value="localhost" /> 
     </identity> 
    </endpoint> 

y el objetivo es obtener un conjunto de dirección de los puntos finales:

List<string> addresses = GetMyCurrentEndpoints(); 

Como resultado tendríamos:

[0] http://mycoolserver/FinancialService.svc 
[1] http://mycoolserver/HumanResourcesService.svc 

Respuesta

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

(Tomado de http://mostlytech.blogspot.com/2007/11/programmatically-enumerate-wcf.html)

17

Esta es mi primera respuesta. Sea amable :)

private List<string> GetMyCurrentEndpoints() 
{ 
    var endpointList = new List<string>(); 

    var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
    var serviceModel = ServiceModelSectionGroup.GetSectionGroup(config); 

    foreach (ChannelEndpointElement endpoint in serviceModel.Client.Endpoints) 
    { 
     endpointList.Add(endpoint.Address.ToString()); 
    } 

    return endpointList; 
} 
+0

¡Agradable! Solo para cualquiera que intente usar esto en la aplicación web, debe tener una ArgumentException como'exePath debe especificarse cuando no se ejecuta dentro de un exe independiente '. Para leer la sección del cliente, @Dmitry tip está bien. ¡Pero también estoy votando tu respuesta! –

Cuestiones relacionadas