You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core项目中WCF服务引用构造函数如何传入服务名称?

.NET Core中WCF服务引用构造函数的正确调用方式

.NET Core下WCF服务引用的配置逻辑和.NET Framework有明显区别,不再依赖name属性标识endpoint,以下是两种可行的调用方式:

方法1:手动构造Binding和EndpointAddress

直接读取appsettings.json中的服务地址和绑定配置,手动实例化服务对象:

// appsettings.json 中的典型配置结构
{
  "WcfServices": {
    "MyDemoService": {
      "ServiceUrl": "http://your-service-address/Service.svc",
      "BindingType": "BasicHttpBinding"
    }
  }
}
// 读取配置
var config = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .Build();

var serviceConfig = config.GetSection("WcfServices:MyDemoService");
var endpointAddr = new EndpointAddress(serviceConfig["ServiceUrl"]);
var binding = new BasicHttpBinding(); // 匹配服务端的绑定类型

// 创建服务客户端实例
var serviceClient = new MyDemoServiceClient(binding, endpointAddr);

方法2:利用配置节名称指定endpoint

如果通过Visual Studio添加服务引用时自动生成了结构化配置,可直接传入配置节的键名来调用构造函数:

// appsettings.json 中多endpoint的配置示例
{
  "MyDemoServiceClient": {
    "EndpointConfigurations": {
      "ProductionEndpoint": {
        "EndpointAddress": "http://prod-service/Service.svc",
        "Binding": {
          "Name": "BasicHttpBinding_IMyDemoService"
        }
      },
      "TestEndpoint": {
        "EndpointAddress": "http://test-service/Service.svc",
        "Binding": {
          "Name": "BasicHttpBinding_IMyDemoService"
        }
      }
    }
  }
}
// 指定使用TestEndpoint配置
var serviceClient = new MyDemoServiceClient("TestEndpoint");

// 若只有默认配置,直接用无参构造函数即可
// var serviceClient = new MyDemoServiceClient();

关键注意点

  • .NET Core不再使用app.config中带name的endpoint节点,配置匹配逻辑基于JSON文件的节结构。
  • 构造客户端时必须保证Binding类型和服务端完全一致(如BasicHttpBinding、WSHttpBinding等),否则会出现通信异常。

内容的提问来源于stack exchange,提问作者The King

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 12:40:13