【问题标题】:Read WCF service endpoint address by name from web.config从 web.config 按名称读取 WCF 服务端点地址
【发布时间】:2013-05-15 18:54:43
【问题描述】:

这里我试图从 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"] 之类的东西,但它不起作用。

【问题讨论】:

  • 你的问题是......?你有错误吗?没有结果?
  • 你只使用 ConfigurationManager 得到它吗?

标签: c# wcf web-config


【解决方案1】:

这就是我使用 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();

【讨论】:

  • 谢谢,少代码!!!,通过名称(不是索引键)获取EndPoint,您的第二个截断代码是一个很好的解决方案。
  • 使用as 进行强制转换可以防止异常。不错。
  • 这很好,但我必须先使用.ToList(),然后它才能让我使用 SingleOrDefault client.Endpoints.Cast().ToList(),以防万一这是其他人的问题跨度>
【解决方案2】:

我猜你实际上必须遍历端点:

string address;
for (int i = 0; i < clientSection.Endpoints.Count; i++)
{
    if (clientSection.Endpoints[i].Name == "SecService")
        address = clientSection.Endpoints[i].Address.ToString();
}

【讨论】:

  • 很好的解决方案。我刚用过。谢谢
【解决方案3】:

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

ThirdServiceClient client = new ThirdServiceClient("ThirdService");

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

【讨论】:

  • 也许 Op 没有客户端代理?
  • 如果您不想使用 ThirdServiceClient 类?只使用 ConfigurationManager 吗?
  • 哦,这来自一个 Microsoft 示例,该示例使用 svcutil.exe 程序针对 Web 服务创建了代理类。我想知道 .Net 库 ThirdServiceClient 的哪个部分 - 但它来自一个示例程序。哎呀,@marc_s,我认为这是我从你那里看到的最难以理解的答案之一。糟糕的一天,呵呵。
猜你喜欢
  • 2013-12-17
  • 1970-01-01
  • 2013-09-14
  • 1970-01-01
  • 1970-01-01
  • 2011-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多