.NET Core 3.1引用含WCF的.NET Framework类库时配置Http Binding报错问询
问题原因
.NET Core 3.1 不存在.NET Framework 专属的system.serviceModel配置节解析逻辑,这就是你收到Unrecognized configuration section system.serviceModel报错的核心原因。.NET Core 及后续.NET 版本的WCF客户端仅支持代码方式配置,不支持直接从app.config读取WCF绑定、端点配置。
可行解决方案
方案1:调整原有.NET Framework类库(推荐)
修改包含WCF服务引用的.NET Framework 3.5类库,将WCF客户端的初始化逻辑从依赖配置改为支持外部传参的代码配置模式,对外暴露必要的可配置项:
- 在类库中封装WCF客户端构造方法,示例代码如下:
using System.ServiceModel; using System.ServiceModel.Channels; // 针对你当前使用的两个服务封装构造逻辑 public static class WcfClientFactory { // 构造ListManagement服务客户端 public static ListManagementAPI.ListManagementSoap CreateListManagementClient(string serviceUrl, bool enableTransportSecurity) { var binding = new BasicHttpBinding(); binding.Security.Mode = enableTransportSecurity ? BasicHttpSecurityMode.Transport : BasicHttpSecurityMode.None; var endpointAddress = new EndpointAddress(serviceUrl); return new ListManagementAPI.ListManagementSoapClient(binding, endpointAddress); } // 构造ContactManagement服务客户端 public static ContactManagementAPI.ContactManagementSoap CreateContactManagementClient(string serviceUrl, bool enableTransportSecurity) { var binding = new BasicHttpBinding(); binding.Security.Mode = enableTransportSecurity ? BasicHttpSecurityMode.Transport : BasicHttpSecurityMode.None; var endpointAddress = new EndpointAddress(serviceUrl); return new ContactManagementAPI.ContactManagementSoapClient(binding, endpointAddress); } }
- 在.NET Core 3.1项目中引用调整后的类库,同时安装必要的WCF依赖NuGet包:
System.ServiceModel.Http、System.ServiceModel.Primitives - .NET Core项目可以选择将配置项写在原生的appsettings.json中,也可以继续沿用你现有app.config的appSettings节点添加配置,读取后传入工厂方法即可。
以appsettings.json配置为例:
{ "WcfConfig": { "ListManagementUrl": "https://ws.caigners.com/listmanagement.asmx", "ListManagementUseTransportSecurity": true, "ContactManagementUrl": "https://ws.caigners.com/contactmanagement.asmx", "ContactManagementUseTransportSecurity": true } }
调用示例:
// 读取配置后构造客户端 var listClient = WcfClientFactory.CreateListManagementClient( _configuration["WcfConfig:ListManagementUrl"], bool.Parse(_configuration["WcfConfig:ListManagementUseTransportSecurity"]) ); // 后续直接调用listClient的服务方法即可
方案2:不修改原有类库,手动解析配置
如果无法调整原有.NET Framework类库的代码,你可以手动读取app.config中的system.serviceModel节点的XML内容,解析出绑定、端点属性后,用反射的方式给类库中的WCF客户端对象赋值绑定和端点地址,该方案改造成本较高,仅作为备选。
内容的提问来源于stack exchange,提问作者Rhydam Dargarh
相关产品推荐
相关产品推荐

