服务参考和可配置的URL

时间:2016-04-18 05:55:29

标签: c# .net

添加服务引用后。在App.config中你会得到这样的结果:

    <client>
        <endpoint address="http://172.31.82.70:8003/TestMatchService/TestMatchService"
            binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ITestMatchService1"
            contract="TestMatchServiceV2.ITestMatchService" name="BasicHttpBinding_ITestMatchService1" />
    </client>

我想添加一个这样的自定义应用设置:

<add key="Server" value="172.31.82.70"/>

如何修改端点以从应用设置中获取IP地址?

1 个答案:

答案 0 :(得分:1)

您可以通过编程方式配置端点,这样您就可以像平常一样从appSettings中读取配置:

// Read this from your config instead...
string server = ConfigurationManager.AppSettings["Server"]
string address = $"http://{server}:8003/TestMatchService/TestMatchService";

var binding = new BasicHttpBinding();
var endpoint = new EndpointAddress(address);
var channelFactory = new ChannelFactory<ITestMatchService>(binding, endpoint);
ITestMatchService client = channelFactory.CreateChannel();

您不再需要配置文件的WCF部分中的任何内容。