首页 > 解决方案 > 在 .net core 项目中按环境加载 WCF 服务

问题描述

在 .NET 核心项目中添加 WCF 时遇到问题。当我过去使用 .net 时,我可以添加多个环境,web.config以便在运行时加载正确的 Web 服务(Dev、Rec、Prod)。

当我将 WCF 服务的引用添加为 Connected Service 时,.net 核心项目中的问题创建了一个文件 ConnectedService.json,其中包含 WCF 服务的 URL。

{
  "ProviderId": "Microsoft.VisualStudio.ConnectedService.Wcf",
  "Version": "15.0.20406.879",
  "GettingStartedDocument": {
    "Uri": "https://go.microsoft.com/fwlink/?linkid=858517"
  },
  "ExtendedData": {
    "Uri": "*****?singleWsdl",
    "Namespace": "Transverse.TokenService",
    "SelectedAccessLevelForGeneratedClass": "Public",
    "GenerateMessageContract": false,
    "ReuseTypesinReferencedAssemblies": true,
    "ReuseTypesinAllReferencedAssemblies": true,
    "CollectionTypeReference": {
      "Item1": "System.Collections.Generic.List`1",
      "Item2": "System.Collections.dll"
    },
    "DictionaryCollectionTypeReference": {
      "Item1": "System.Collections.Generic.Dictionary`2",
      "Item2": "System.Collections.dll"
    },
    "CheckedReferencedAssemblies": [],
    "InstanceId": null,
    "Name": "Transverse.TokenService",
    "Metadata": {}
  }
}

我的问题是如何根据使用的环境加载正确的服务。

笔记。

在我的项目中,我没有appsettingsweb 配置。它是一个 .net 核心类库,在 ASP.NET 核心应用程序中被称为中间件。

标签: c#.netwcfasp.net-core

解决方案


正如我从这篇文章中了解到的,这是微软的建议:

  1. 添加新的类文件
  2. 添加服务reference.cs的相同命名空间
  3. 添加 Partial Class 以扩展引用服务类(在 Reference.cs 中声明)
  4. 以及实现 ConfigureEndpoint() 的 Partial 方法(在 Reference.cs 中声明)
  5. ConfigureEndpoint()通过为 Endpoint 设置新值来实现方法

例子:

namespace Your_Reference_Service_Namespace
{
    public partial class Your_Reference_Service_Client
    {
        static partial void ConfigureEndpoint(System.ServiceModel.Description.ServiceEndpoint serviceEndpoint, System.ServiceModel.Description.ClientCredentials clientCredentials)
        {
            serviceEndpoint.Address = 
                new System.ServiceModel.EndpointAddress(new System.Uri("http://your_web_service_address"), 
                new System.ServiceModel.DnsEndpointIdentity(""));
        }
    }
}
  1. 在这里,您可以从appsettings.json文件中获取值

    新 System.Uri(configuration.GetValue("yourServiceAddress")


推荐阅读