c# - 在代码中覆盖配置文件 WCF 基地址

标签 c# .net wcf wcf-endpoint

我有一个 WCF Windows 服务,其端点在服务的配置文件中指定。

<baseAddresses>
    <add baseAddress="net.tcp://localhost:9000/MyEndpoint"/>
</baseAddresses>

一切正常。但是,在某些情况下,端口 9000 可能已在使用中,这会导致 ServiceHost 在 Open() 上失败。 我需要能够覆盖代码中配置文件中指定的默认基址。例如假设环境变量包含要使用的端口号。

有没有办法以编程方式执行此操作?

构建 ServiceHost 后,我​​可以看到 BaseAddresses 属性,它返回从配置文件中获取的 Uri 列表。但是,这是一个只读集合,因此不能用于更改默认值。

如果我在 ServiceHost 构造函数中指定替换 Uri,我会得到

This collection already contains an address with scheme net.tcp. There can be at most one address per scheme in this collection. If your service is being hosted in IIS you can fix the problem by setting 'system.serviceModel/serviceHostingEnvironment/multipleSiteBindingsEnabled' to true or specifying 'system.serviceModel/serviceHostingEnvironment/baseAddressPrefixFilters'.

如果我创建一个 CustomServiceHost 并尝试设置替换基地址,我会得到同样的错误。

class CustomHost : ServiceHost
{
    public CustomHost(Type serviceType) : base (serviceType)         
    {
    }
    protected override void ApplyConfiguration()
    {
        base.ApplyConfiguration();

        this.AddBaseAddress(new Uri("net.tcp://localhost:9010/MyEndpoint"));
    }
}

我知道,如果我将配置文件基地址留空并将基地址传递给 ServiceHost 构造函数,那么就可以正常工作 - 即我可以指定新的基地址。但是,我想使用配置文件来指定默认值(而不是硬编码)。

最佳答案

看看我发布的这个例子。它有一个完全通过代码配置的 WCF 服务的完整工作示例。然后,您应该能够使用 Environment.GetEnvironmentVariable 获取端口号并将其传递给 ServiceHost 的构造函数:

Possible to have same contract, same binding, same address, but different ports?

关于c# - 在代码中覆盖配置文件 WCF 基地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3086160/

相关文章:

c# - 有条件地调用 Linq 扩展方法

.net - 如何开始使用 WCF/WPF?

wcf - 25 个并发异步 WCF 调用以使用任务进行编排

.net - 如何退出或关闭(而不是杀死)Word文档(进程)?

asp.net - 提供的 URI 方案 'https' 无效;预期 'http' 。参数名称 : via

asp.net - 无法使用权​​限 'site.com' 为 SSL/TLS 建立安全通道

c# - @: and <text> in Razor 之间的区别

c# - HashSet<T> 是否与 List<T> 相同但具有唯一性?

c# - 在 C# 中创建 AI 行为树 - 如何?

c# - 修改注册表键值