gpt4 book ai didi

c# - 以编程方式从 wcf 配置文件中的单独服务获取基地址的值

转载 作者:行者123 更新时间:2023-12-01 18:50:07 25 4
gpt4 key购买 nike

假设我有以下 wcf 配置文件

<services>
<service name="Service" behaviorConfiguration="Default">
<endpoint address="rest" behaviorConfiguration="Default" binding="webHttpBinding" bindingConfiguration="WebBinding" contract="CaptureService"/>
<host>
<baseAddresses>
<add baseAddress="http://localhost:8501/service/service1.svc"/>
</baseAddresses>
</host>
</service>
<service name="otherService" behaviorConfiguration="Default">
<endpoint address="start" behaviorConfiguration="Default" binding="webHttpBinding" bindingConfiguration="WebBinding" contract="CaptureService"/>
<host>
<baseAddresses>
<add baseAddress="http://localhost:8501/service/service2.svc"/>
</baseAddresses>
</host>
</service>
</services>

如何循环配置以检索基本地址的值?这是我想要执行此操作的方法:

    public ServiceHost()
{
//read the config here

this.service = svcType;
this.scheme = new UriSchemeKeyedCollection(//list of values here);

//add certain behaviours
base.InitializeDescription(this.service, this.scheme);
this.Description.Behaviors.Add(this);
}

不过,我觉得我的处理方式可能完全错误。有人认为这有什么本质上的错误吗?

最佳答案

您可以阅读配置文件,选择 system.serviceModel 部分,然后转到 services 及其 host 元素,最后到他们的baseAddresses:

private static Uri[] GetBaseAddresses()
{
// Get the application configuration file.
// TODO: Might be adjusted for WCF hosted / web.config
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

// Get the collection of the section groups.
var sectionGroups = config.SectionGroups;

// Get the serviceModel section
var serviceModelSection = sectionGroups.OfType<ServiceModelSectionGroup>().SingleOrDefault();

// Check if serviceModel section is configured
if (serviceModelSection == null)
throw new ArgumentNullException("Configuration section 'system.serviceModel' is missing.");

// Get base addresses
return (from ServiceElement service in serviceModelSection.Services.Services
from BaseAddressElement baseAddress in service.Host.BaseAddresses
select new Uri(baseAddress.BaseAddress)).ToArray();
}

然后只需在构造函数中使用该方法即可:

this.scheme = new UriSchemeKeyedCollection(GetBaseAddresses());

关于c# - 以编程方式从 wcf 配置文件中的单独服务获取基地址的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24649979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com