C# 从web.config按名称读取WCF服务端点地址

C# 从web.config按名称读取WCF服务端点地址,c#,wcf,web-config,C#,Wcf,Web Config,在这里,我试图从web.config中按名称读取我的服务端点地址 ClientSection clientSection = (ClientSection)ConfigurationManager.GetSection("system.serviceModel/client"); var el = clientSection.Endpoints("SecService"); // I don't want to use index here as more endpoints may get a

在这里,我试图从web.config中按名称读取我的服务端点地址

ClientSection clientSection = (ClientSection)ConfigurationManager.GetSection("system.serviceModel/client");
var el = clientSection.Endpoints("SecService"); // I don't want to use index here as more endpoints may get added and its order may change
string addr = el.Address.ToString();
有没有一种方法可以根据名称读取端点地址

这是我的
web.config
文件

<system.serviceModel>
 <client>
     <endpoint address="https://....................../FirstService.svc" binding="wsHttpBinding" bindingConfiguration="1ServiceBinding" contract="abc.firstContractName" behaviorConfiguration="FirstServiceBehavior" name="FirstService" />
     <endpoint address="https://....................../SecService.svc" binding="wsHttpBinding" bindingConfiguration="2ServiceBinding" contract="abc.secContractName" behaviorConfiguration="SecServiceBehavior" name="SecService" />
     <endpoint address="https://....................../ThirdService.svc" binding="wsHttpBinding" bindingConfiguration="3ServiceBinding" contract="abc.3rdContractName" behaviorConfiguration="ThirdServiceBehavior" name="ThirdService" />
            </client>
    </system.serviceModel>

这将有效
clientSection.Endpoints[0],但我正在寻找一种按名称检索的方法


例如,类似于
clientSection.Endpoints[“SecService”]
,但它不起作用。

我想您必须实际遍历端点:

string address;
for (int i = 0; i < clientSection.Endpoints.Count; i++)
{
    if (clientSection.Endpoints[i].Name == "SecService")
        address = clientSection.Endpoints[i].Address.ToString();
}
字符串地址;
for(int i=0;i
好吧,每个客户端端点都有一个名称——只需使用该名称实例化您的客户端代理即可:

ThirdServiceClient client = new ThirdServiceClient("ThirdService");

这样做将自动从配置文件中读取正确的信息。

这就是我使用Linq和C#6所做的

首先获取客户端部分:

var client = ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection;
然后获取等于endpointName的端点:

var qasEndpoint = client.Endpoints.Cast<ChannelEndpointElement>()
    .SingleOrDefault(endpoint => endpoint.Name == endpointName);
您还可以使用以下命令从端点接口获取端点名称:

var endpointName = typeof (EndpointInterface).ToString();

你的问题是。。。。?你有错误吗?没有结果?是否仅使用ConfigurationManager获得?可能Op没有客户端代理?如果不想使用ThirdServiceClient类?仅使用ConfigurationManager?哦,这来自一个Microsoft示例,该示例针对web服务使用
svcuti.exe
程序创建了代理类。我想知道.Net库ThirdServiceClient的哪一部分,但它来自一个示例程序。哎呀,@marc_s,我想这是我从你身上看到的最令人费解的答案之一。糟糕的一天,好办法。我刚用过。谢谢你,少点代码!!!,要按名称(而不是索引键)获取
端点
,您的第二个截断代码是一个很好的解决方案。使用
as
进行强制转换可以防止异常。很好。这很好,但我必须先使用.ToList(),然后才能使用SingleOrDefault client.Endpoints.Cast().ToList(),以防这是其他人的问题
var endpointName = typeof (EndpointInterface).ToString();