21

在这里,我试图从 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"],但它不工作。

4

3 回答 3

22

这就是我使用 Linq 和 C# 6 的方式。

首先获取客户端部分:

var client = ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection;

然后获取等于endpointName的端点:

var qasEndpoint = client.Endpoints.Cast<ChannelEndpointElement>()
    .SingleOrDefault(endpoint => endpoint.Name == endpointName);

然后从端点获取 url:

var endpointUrl = qasEndpoint?.Address.AbsoluteUri;

您还可以使用以下方法从端点接口获取端点名称:

var endpointName = typeof (EndpointInterface).ToString();
于 2016-03-07T03:28:06.510 回答
17

我猜你必须真正遍历端点:

string address;
for (int i = 0; i < clientSection.Endpoints.Count; i++)
{
    if (clientSection.Endpoints[i].Name == "SecService")
        address = clientSection.Endpoints[i].Address.ToString();
}
于 2013-05-15T19:01:49.227 回答
5

好吧,每个客户端端点都有一个名称- 只需使用该名称实例化您的客户端代理:

ThirdServiceClient client = new ThirdServiceClient("ThirdService");

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

于 2013-05-15T19:02:02.877 回答