c# - 在 .net 核心项目中按环境加载 WCF 服务

标签 c# .net wcf asp.net-core

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

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

{
  "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": {}
  }
}

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

注意。

在我的项目中,我没有 appsettings 也没有 web 配置。它是一个 .net 核心类库,在 ASP.NET 核心应用程序中作为中间件调用。

最佳答案

据我了解 this article ,这是微软的建议:

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

例子:

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 文件中获取值

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

关于c# - 在 .net 核心项目中按环境加载 WCF 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51783546/

相关文章:

c# - 如何获取对象具有的属性数?

java - 将警报推送到 Java 中的通知托盘应用程序

android - 在 android studio 中反序列化操作 wcf 的请求消息正文时出错

c# - 是否可以在有人连接之前在 WCF 服务中执行启动代码?

c# - 如何对集合的保存进行单元测试

c# - 命名为String.Format,可能吗?

c# - 如何使用 asp.net 序列化反序列化具有值和属性的 xml 节点

C# 在方法中初始化一个 const 变量

c# - .Net 应用程序范围的变量

c# - 在 ASP.NET MVC 中通过重定向传递复杂对象?