c# - 从 web.config 按名称读取 WCF 服务终结点地址

标签 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 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"],但它不起作用。

最佳答案

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

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

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

关于c# - 从 web.config 按名称读取 WCF 服务终结点地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16572890/

相关文章:

asp.net-core - 如何从 web.config、API 调用返回 index.html 复制 .​​net 核心启动中的重写规则

c# - 截取未打开的文件夹窗口的屏幕截图

c# - System.InvalidOperationException : XmlSerializer attribute System. Xml.Serialization.XmlChoiceIdentifierAttribute 在项目中无效

wpf - 如何确保所有模型都可以访问服务代理?

c# - WCF 客户端和服务器

c# - Web.config 递归拒绝访问子文件夹

.net - 我可以从 Azure Web 角色入口点访问 web.config 吗?

c# - 检测用于创建 RegEx 的文件名模式

c# - 使用 .NET Core 进行 Hangfire 依赖注入(inject)

c# - 使用 MSDASC.DLL 时应如何修复 "At least one of the arguments for ' .. .' cannot be marshaled"错误