c# - 将服务配置从配置移至代码
问题描述
我的 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);
这适用于第一部分,但随后因使用不正确的消息版本而失败。我可以看到这是在自定义绑定中定义的,但我不确定如何将此绑定转换为我的代码。我确实尝试了很多,但到目前为止没有结果。
有谁知道如何做到这一点?
解决方案
我建议您利用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>
,你可以删除临时文件。
推荐阅读
- django-rest-framework - Django中嵌套JSON的序列化
- python - 无法更改 numpy 数组中字符串的大小
- scala - 使用 Scala 连接具有特定数量寄存器的列
- capl - CAPL 测量从睡眠到唤醒 LIN 的时间
- routes - 如何在 Angular 8 中使用 RouterLinkActive?
- python-3.x - 使用熊猫数据框时出现 KeyError
- r - 有效地将高斯噪声添加到矩阵行的每个元素
- javascript - 我无法在 mongodb 服务器中添加第一个用户
- fortran - 用 fortran 编写的 read 语句中的隐含 do 语句
- docker - docker server (kong) 启动后运行 curl 命令