首页 > 解决方案 > 将服务配置从配置移至代码

问题描述

我的 app.config 中有以下配置:

<bindings>
  <customBinding>
    <binding name="myBinding">
      <textMessageEncoding messageVersion="Soap12"/>
      <httpTransport/>
    </binding>
  </customBinding>
  <wsHttpBinding>
    <binding name="myBinding" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Text" textEncoding="utf-8">
      <security mode="Transport">
        <transport clientCredentialType="Windows"/>
      </security>
    </binding>
  </wsHttpBinding>
</bindings>
<client>
  <endpoint address="/../" binding="wsHttpBinding" bindingConfiguration="myBinding" contract="myContract" name="myName"/>
</client>

使用此配置,服务按预期工作。

由于多种原因,我无法在生产环境中使用 app.config 文件,因此我想改为在 c# 中定义绑定。我做了以下事情:

        var binding = new BasicHttpBinding();
        var address = new EndpointAddress(url);

        binding.Security = new BasicHttpSecurity() { Mode = BasicHttpSecurityMode.Transport };
        binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;

        var client = new MyClient(binding, address);

这适用于第一部分,但随后因使用不正确的消息版本而失败。我可以看到这是在自定义绑定中定义的,但我不确定如何将此绑定转换为我的代码。我确实尝试了很多,但到目前为止没有结果。

有谁知道如何做到这一点?

标签: c#wcf

解决方案


我建议您利用ConfigurationChannelFactory<TChannel>该类来配置您的客户端,使用来自 app.config 文件以外的源的 XML 配置(例如,从数据库、可执行文件中的资源或其他自定义源读取的 XML 字符串)。

恕我直言,XML 格式比使用代码构建的配置更易于阅读和维护。

为此,步骤如下:

  • 获取包含您的 XML 配置数据的字符串,例如:

    string configurationData = @"<configuration>
        <system.serviceModel>
        ...
        ";
    
  • 将其保存到临时文件:

    var tempFileName = Path.GetTempFileName();
    File.WriteAllText(tempFileName, configurationData);
    
  • System.Configuration.Configuration从临时文件生成一个对象:

    var filemap = new ExeConfigurationFileMap
    {
        ExeConfigFilename = tempFileName
    };
    var config = ConfigurationManager.OpenMappedExeConfiguration(filemap, ConfigurationUserLevel.None);
    
  • ChannelFactory<TChannel>从配置创建一个:

    var channelFactory = new ConfigurationChannelFactory<TChannel>(endpointConfigurationName, config, remoteAddress);
    
  • 一旦你创建了你的ChannelFactory<TChannel>,你可以删除临时文件。


推荐阅读