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

ASP.NET 7.0 Web API按环境从appsettings.json动态加载WSDL URL

解决ASP.NET 7.0 Web API中WSDL URL的多环境动态配置问题

1. 在配置文件中添加多环境URL

分别在appsettings.json、appsettings.Development.json、appsettings.Production.json中配置对应环境的服务地址:

主配置文件appsettings.json(默认兜底值):

{
  "ServiceSettings": {
    "UMarketSCServiceUrl": "http://default-url/services/umarketsc"
  }
}

开发环境appsettings.Development.json:

{
  "ServiceSettings": {
    "UMarketSCServiceUrl": "http://dev.xx.xx.xx:xxxx/services/umarketsc"
  }
}

生产环境appsettings.Production.json:

{
  "ServiceSettings": {
    "UMarketSCServiceUrl": "http://prod.xx.xx.xx:xxxx/services/umarketsc"
  }
}

2. 替换硬编码的Endpoint地址逻辑

自动生成的Reference.cs是partial类,直接修改会被后续重新生成覆盖,因此通过创建同名partial类扩展逻辑:

创建新文件(如UMarketSCClient.Extensions.cs),与自动生成的客户端类保持同命名空间:

using Microsoft.Extensions.Configuration;
using System.ServiceModel;

namespace YourServiceNamespace // 替换为Reference.cs中的实际命名空间
{
    public partial class UMarketSCClient
    {
        // 通过依赖注入获取配置,替换静态地址逻辑
        public static EndpointAddress GetDynamicEndpointAddress(EndpointConfiguration endpointConfiguration)
        {
            var configBuilder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
                .Build();

            if (endpointConfiguration == EndpointConfiguration.UMarketSC)
            {
                var serviceUrl = configBuilder["ServiceSettings:UMarketSCServiceUrl"] 
                    ?? throw new InvalidOperationException("未配置UMarketSC服务地址");
                return new EndpointAddress(serviceUrl);
            }

            throw new InvalidOperationException($"找不到名称为'{endpointConfiguration}'的端点");
        }
    }
}

更优雅的依赖注入方式

在Program.cs中注册客户端实例时直接绑定配置地址:

builder.Services.AddScoped<UMarketSCClient>(sp =>
{
    var config = sp.GetRequiredService<IConfiguration>();
    var serviceUrl = config["ServiceSettings:UMarketSCServiceUrl"] 
        ?? throw new InvalidOperationException("未配置UMarketSC服务地址");
    
    // 根据实际服务绑定类型调整,如BasicHttpBinding/WSHttpBinding等
    var binding = new BasicHttpBinding();
    return new UMarketSCClient(binding, new EndpointAddress(serviceUrl));
});

后续业务代码中直接通过依赖注入获取客户端实例,即可自动使用当前环境的URL。

3. 关于ConnectedService.json的说明

该文件中的URL是生成服务引用时使用的WSDL地址,仅用于生成客户端代码。如果需要在不同环境生成时使用对应WSDL,可通过命令行指定:

  • 开发环境生成命令:
dotnet svcutil http://dev.xx.xx.xx:xxxx/services/umarketsc?wsdl -o Reference.cs -cs ConnectedService.json
  • 生产环境生成时替换为对应WSDL URL即可。

内容的提问来源于stack exchange,提问作者Salman Rafique

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 15:15:21